✅ Day 606: Accepted on Codeforces! Problem B — Not Dividing | Round 856 (Div. 2) Divisibility, minimality, and a sneaky edge case — this problem packs a lot into a compact solution! 🔢 Let me walk you through the thinking! 🔗Problem Link: https://lnkd.in/gTYKfHTc 🧩 The Problem: Given an array of n positive integers, modify each element (by increasing it) with the minimum total number of increments such that no element divides any other element in the array. Find the resulting array! 💡 My Approach — Two-Pass Greedy: The Critical Observation: 1 divides everything! Any element equal to 1 must be increased first — it will always divide every other element, making a solution impossible unless we fix it. The minimum fix: bump all 1s to 2. ✅ Pass 1 — Fix all 1s: python for i in range(n): if a[i] == 1: a[i] = 2 Pass 2 — Fix divisibility between adjacent elements: After sorting (implicit in the problem structure), scan left to right. If a[i+1] % a[i] == 0 (next element is divisible by current), increment a[i+1] by 1 to break the divisibility: python for i in range(n-1): if a[i+1] % a[i] == 0: a[i+1] += 1 Why only check adjacent pairs? Because we process left to right on a sorted (or near-sorted) array — if a[i] doesn't divide a[i+1], it can't divide anything further right either (they're larger). One pass is sufficient! 🎯 Examples: [2, 4, 3, 6] → 4%2=0 → 4→5, 6%3=0 → 6→7 → [2, 5, 3, 7] ✅ [1, 2, 3] → 1→2, then 2%2=0 → 2→3, 3%3=0 → 3→4 → [2, 3, 4] ✅ [4, 2] → 4%2=0... wait, array is processed as given — [4, 2] → 2%4≠0 → [4, 2] ✅ 📌 Key Takeaways: 🔢 Always handle edge cases first — the value 1 is a special divisor of everything. Spotting and neutralising this edge case immediately simplifies all subsequent logic! 🕵️ 🔢 Greedy + single pass works because incrementing by just 1 is the minimum change, and after fixing a[i+1], it can only grow — never shrink — so earlier fixes stay valid! ✅ 🔢 Adjacent checking suffices on sorted input — divisibility violations in sorted arrays only occur between elements close in value. One left-to-right pass catches all violations! 🎯 🤯 The "Aha!" Moment: The entire problem collapses into two simple rules: kill all 1s first, then fix adjacent divisibility with a +1 nudge. Two passes, zero complex data structures, pure logic! 🧠 📧 sanjaykasaudhan09@gmail.com 📱 +91-9170580657 📋 Connect with me: https://lnkd.in/g_dRWtri #Codeforces #CompetitiveProgramming #Python #Divisibility #Greedy #NumberTheory #DSA #ProblemSolving #Accepted #CodingJourney #Programming
Divisibility Problem Solution on Codeforces: Greedy Approach
More Relevant Posts
-
update from previous post[https://lnkd.in/dVx_NrDQ] From "Arrow Code" to Clean Architecture. 🏹 ➡️ 🧱 I’ve hit a major turning point in my Python journey. I realized my code was starting to look like an arrow—layers upon layers of if statements and while loops pushing my logic further and further to the right. In professional dev circles, they call this Arrow Code, and it's a nightmare to maintain. Here’s how I "flattened" my latest project: ✅ Decomposition: I broke down massive, nested blocks into small, dedicated functions. Each function now does one thing well, making the main logic readable at a single glance. ✅ The "Gatekeeper" Pattern: Instead of scattered validation, I built a centralized handler to act as a security guard for all user inputs. ✅ State Management: I’m now mastering the "Baton Pass"—using return values and arguments to move data (like budgets) safely through the app instead of relying on global variables. ✅ Professional Workflow: I’m officially using Git branches and Pull Requests on GitHub to review my own work and track my architectural improvements. The goal isn't just to write code that the computer understands; it’s to write code that other humans can read. 🚀 #CleanCode #Python #SoftwareEngineering #Refactoring #CodingJourney #BuildInPublic
To view or add a comment, sign in
-
-
I built a RAG layer for Claude Code that cuts token usage by 80–90% Most devs using Claude Code don't realize they're burning tokens on files Claude doesn't need to read. Ask Claude "how does auth work?" and it reads 3 full files — 1,500+ tokens just to answer with 40 relevant lines. I fixed that. What I built: A local hybrid RAG system that sits between Claude and your codebase: → Late chunking — splits every file into overlapping 40-line windows → Dense retrieval — semantic search with all-MiniLM-L6-v2 (runs fully local, no API key) → BM25 sparse retrieval — keyword matching for exact symbol names → Cross-encoder reranking — picks the 3 best chunks from 20 candidates → File watcher — auto-rebuilds the index within 2 seconds of any file save Claude Code reads the CLAUDE.md and knows: run pip package before opening any file. It gets back 3 precise snippets with file path + line range. It reads only those lines. Nothing else. Real numbers on my Volta Engine project (76 files): - Without RAG: 17,235 chars across 3 files for one question - With RAG: 3,073 chars the exact 3 chunks that matter - 82% fewer tokens. Same answer. The whole thing runs offline. No cloud embeddings. No API calls. Just a one time pip install and run it. Stack: sentence-transformers · rank-bm25 · watchdog · Python If you use Claude Code daily on a real codebase, this pays for itself in the first session. DM me if you want the scripts. 🧠 #AI #ClaudeCode #RAG #DeveloperTools #Python #LLM #Productivity
To view or add a comment, sign in
-
🚀 Cracked LeetCode 18 : 4Sum — From Naive to Optimal Approach Today I worked on the classic 4Sum problem — finding all unique quadruplets that sum to a target. 🔴 Naive Approach (Brute Force) Think of checking every possible quadruplet: Use 4 loops (i, j, k, l) Check if sum == target Store unique results using a set ⏱️ Time Complexity: O(n⁴) 👉 Works, but too slow for large inputs. 🟡 Better Approach (Hashing) Fix 2 elements Use a HashSet for remaining 2 elements (like 2Sum) ⏱️ Time Complexity: O(n³) 👉 Faster, but still not optimal. 🟢 Optimal Approach (Sorting + Two Pointers) 💡 Idea: Sort the array Fix first two numbers (i, j) Use two pointers (k, l) to find remaining pair ⏱️ Time Complexity: O(n³) But much faster in practice due to pruning & skipping duplicates. 💻 Pseudo Code (Easy to Understand): sort array for i from 0 to n-1: skip duplicates for i for j from i+1 to n-1: skip duplicates for j k = j + 1 l = n - 1 while k < l: sum = arr[i] + arr[j] + arr[k] + arr[l] if sum == target: store answer k++, l-- skip duplicates for k and l else if sum < target: k++ else: l-- 🔥 Key Interview Insight 👉 “Sort + Fix elements + Reduce to 2Sum using two pointers” #DataStructures #Algorithms #Java #LeetCode #CodingInterview #100DaysOfCode
To view or add a comment, sign in
-
Day 11/30 🔹 Problem: Build a calculator using functions 🔹 What I focused on today: Breaking a problem into small reusable functions and controlling flow using a menu 🔹 My Thinking Process: Create separate functions for each operation (add, subtract, multiply, divide) Show a menu to the user Take user choice Call the corresponding function 👉 Functions + menu = clean and organized program 🔹 Inputs I used: Two numbers Operation choice 🔹 Code: def add(a, b): return a + b def subtract(a, b): return a - b def multiply(a, b): return a * b def divide(a, b): if b == 0: return "Cannot divide by zero" return a / b print("1. Add") print("2. Subtract") print("3. Multiply") print("4. Divide") choice = input("Enter your choice: ") num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) if choice == "1": print("Result:", add(num1, num2)) elif choice == "2": print("Result:", subtract(num1, num2)) elif choice == "3": print("Result:", multiply(num1, num2)) elif choice == "4": print("Result:", divide(num1, num2)) else: print("Invalid choice") 🔹 Example: Choice = 1, Numbers = 10 and 5 Output → 15 🔹 Key Takeaway: Using functions makes code modular, reusable, and easier to manage, especially when multiple operations are involved #Day11 #Python #30DaysOfCode #LearningInPublic #DataAnalytics #ProblemSolving
To view or add a comment, sign in
-
🚨Breaking: The fastest repo in history just dropped. claw-code crossed 50K stars in under 2 hours and it's not just another Claude Code fork. This is a clean-room rewrite of the Claude Code harness ported from scratch — first to Python, now moving to Rust. No leaked snapshot. No archived source. Just architecture replication. Backstory is wild: The author woke up at 4 AM to the Claude Code source exposure chaos community panicking legal concerns everywhere repos getting mirrored and taken down So instead of forking the leaked code — he rebuilt the core harness from scratch and pushed it before sunrise. The entire rewrite was orchestrated using oh-my-codex (OmX) • team mode for parallel reviews • ralph mode for persistent execution loops • architect-level verification • codex-driven implementation Result: A clean Python agent harness with: • command system • tool registry • query engine • task orchestration • CLI entrypoint • parity audit tooling • subsystem manifest • runtime architecture mapping And now they’re rewriting the runtime in Rust for a faster, memory-safe agent harness. The repo exploded: 84k+ stars 82k forks < 3 hours old This isn’t just preserving Claude Code. It’s turning the agent harness into an open, portable architecture. Python first Rust next fully independent runtime This space is moving very fast. Repo Link in comments:👇
To view or add a comment, sign in
-
-
My CLAUDE.md was 281 lines. Claude loaded all of it every session - whether I was writing a post or debugging a Python script. Post rules. Format guides. Note conventions. Voice guidelines. All in context, all the time. Even when none of it was relevant. Longer context = lower adherence. The docs say it plainly. I ignored it until I ran this prompt: --- *Review my CLAUDE.md against https://lnkd.in/g6UNtsC7 and suggest specific improvements - what to add, what to move to .claude/rules/ files, and what to cut.* --- Claude read the official docs, compared them against my file, and came back with a diagnosis. The biggest one was `.claude/rules/` - a directory most people don't know exists. Here's what it told me to do: Rules in `.claude/rules/` load just like CLAUDE.md - but you can scope them to specific file paths. ``` paths: - "posts/**" ``` That one frontmatter block means post rules only enter context when Claude is working inside that folder. Format guides, note conventions - same thing. Zero tokens wasted when they don't apply. After the restructure: - CLAUDE.md: 281 lines → 69 lines - Always-loaded context: ~180 lines total - 3 rule files load on demand, only when relevant The path-scoped rules are in the official docs at https://lnkd.in/g6UNtsC7. Almost nobody uses them. Run `/memory` in Claude Code to see exactly what's loaded in your current session. If it's over 200 lines, that's where the drift is coming from. What rule do you keep repeating to Claude because it keeps forgetting? #ClaudeAI #AITools #BuildInPublic #ProductManagement #DeveloperTools
To view or add a comment, sign in
-
-
My first version of the Task Manager CLI was embarrassing. Everything in one file. No error handling. Variables named x, temp, data2. It worked — until it didn't. And when it broke, I had no idea where to start debugging. That moment of staring at my own code and not understanding it was one of the most important moments in my development as an engineer. I refactored the entire project. Broke it into modules. Added structured exception handling. Rewrote the validation logic. Debugging effort dropped by 40%. More importantly, I could actually read my own code. The lesson wasn't technical. It was about ego. Bad code is often the result of being in a hurry to "finish" — instead of being willing to do it right. I now build slower and ship cleaner. And I'm better for it. Have you ever looked back at old code and learned something important about yourself? #Refactoring #CleanCode #Python #SoftwareEngineering #LessonsLearned
To view or add a comment, sign in
-
🚀 Solved LeetCode 2515 – Shortest Distance to Target String in a Circular Array Today I tackled an interesting problem that highlights the importance of handling circular data structures efficiently. 🔍 Problem Insight: Given a circular array of words, a target string, and a starting index, the goal is to find the minimum number of steps required to reach the target by moving either left or right. 💡 Key Learnings: Circular arrays require thinking beyond linear traversal Always consider both directions (forward & backward) Optimizing distance using min(distance, n - distance) is the key trick Simple logic + correct observation = optimal solution ⚙️ Approach Used: Traverse the array to find all occurrences of the target Calculate distance from the starting index Take the minimum considering circular movement 📈 Complexity: Efficient O(n) solution with constant space 🔥 Takeaway: This problem reinforced how small tweaks (like circular behavior) can change the entire approach. A great example of combining logic + observation for clean and optimal solutions. #LeetCode #Algorithms #ProblemSolving #CodingJourney #Java #DataStructures #CompetitiveProgramming
To view or add a comment, sign in
-
-
#ClaudeCode has been leaked yesterday. The engineer who noticed the leak is rewriting the codebase in Python & Rust to avoid takedown. It's the fastest growing repo in history, 𝟴𝟭𝗸 𝘀𝘁𝗮𝗿𝘀 now 28 hours since the leak. There's a good reason for that - Claude Code has been the best in class solution for a long time. There are some interesting unreleased features. Among them daemon mode (background OS process) and heartbeat - suggesting moving the product in the direction paved by OpenClaw. I don't find the new features groundbreaking - if you were following Claude Code development closely this all makes sense. ▪️▪️ 𝗦𝗼 𝘄𝗵𝗲𝗿𝗲 𝗶𝘀 𝗖𝗹𝗮𝘂𝗱𝗲'𝘀 𝗰𝗼𝗺𝗽𝗲𝘁𝗶𝘁𝗶𝘃𝗲 𝗲𝗱𝗴𝗲? Why is it best in class if competitors are already using Opus 4.6? Good engineering and feature-richness 🌀 184 tools and 207 slash commands 🌀 29 subsystems (564 utils, 389 modules, 130 services) 🌀 104 hooks for deep lifecycle integration 🌀 Sophisticated codebase navigation & memory system 〰️〰️ 𝗦𝘆𝘀𝘁𝗲𝗺 𝗽𝗿𝗼𝗺𝗽𝘁 𝗮𝘀𝘀𝗲𝗺𝗯𝗹𝘆 The key to building agents is context engineering. Not too little, not too much - just right. Claude Code has concise core system prompt, but allows the user to dynamically assemble context based on the task and project. System prompts were leaked in October last year, but at that time Claude Code was way less mature. 〰️〰️ 𝗔𝗴𝗲𝗻𝘁 𝘀𝘂𝗯𝘀𝘆𝘀𝘁𝗲𝗺 The agent architecture is built on 20 dedicated modules. Sub-agents aren't just prompts; they are first-class tools spawned as isolated OS threads with restricted permissions. With 6 built-in types (Explore, Plan, Verification, etc.), the parent process never blocks—communication happens via filesystem manifests. It includes persistent memory, task resumption, and "Team tools" for coordinated multi-agent orchestration. 〰️〰️ 𝗕𝗿𝗶𝗱𝗴𝗲 𝘀𝘂𝗯𝘀𝘆𝘀𝘁𝗲𝗺 This is the infrastructure behind the "𝗞𝗔𝗜𝗥𝗢𝗦" daemon mode. Comprising 31 modules, it transforms Claude Code from a local CLI into a remotely-controllable daemon via JWT auth and WebSocket transports. Claude Code is evolving into a persistent cloud agent you can interact with via Telegram, Discord, or Slack. ▪️▪️ 𝗦𝗵𝗼𝘂𝗹𝗱 𝘆𝗼𝘂 𝗮𝗻𝗮𝗹𝘆𝘇𝗲 𝘁𝗵𝗲 𝗰𝗼𝗱𝗲𝗯𝗮𝘀𝗲? Unless you're building similar tools, probably not. But you will benefit from this leak, because builders all over the world will incorporate these ideas into the systems you'll be using. Until then probably the most cost-efficient approach is to just follow Claude's new features. Extremely powerful ones are already here. Claude Code is a sophisticated, powerful tool - but it does have a learning curve. Coding agents are the largest force multiplier since the invention of the Second Monitor. The future is now. Don't miss it.
To view or add a comment, sign in
-
-
On Monday, $2.5 billion worth of code got leaked… Context: Someone pulled the full source code of Claude Code from a file Anthropic left in a public package. By Tuesday, a developer had rewritten the whole thing in Python and Rust. His repo hit 100,000 GitHub stars in one day. Now everyone can replicate Claude Code… Sounds like a big deal - but my hot take: It’s a nothing burger 🍔 Why it’s a nothing burger: Anthropic ships fast. 90% of Claude Code was written by itself. The codebase probably turns over every 2-3 months. The $2.5 Billion of ARR of Claude Code is defensible and expanding, not because of their existing code base - but because of the speed and precision the product improves with every week. Anthropic’s secret sauce is their ways of improving, not their current code-base. I love their product for its slope, not its intercept. This situation is a sign of where product is heading due to AI. When software is blazingly fast and free to build, the code itself is worthless. Lesson to CPOs: Protect and nurture your people and product approaches - not your code 🤯
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development