🚀 Binary Search | Clean Thinking > Complex Code Just solved the classic Binary Search LeetCode Problem 704 with 100% test cases passing and optimal runtime. Here’s a structured breakdown of my approach 👇 🎯 Problem Goal Find the index of a target element in a sorted array using an efficient approach. 🧠 My Approach 1. Define the Search Space → Initialize low = 0, high = n - 1 2. Apply Binary Search Logic → Compute mid → Compare target with nums[mid] → Eliminate half of the search space each step 3. Maintain Clean Boundaries → Move low or high precisely to avoid infinite loops 4. Exit Condition → Return index if found → Else return -1 ⚡ What I Focused On • Writing minimal, readable code • Avoiding unnecessary conditions • Staying calm and methodical • Trusting fundamentals over shortcuts 💡 Key Takeaway Strong fundamentals + structured thinking = fast and reliable problem solving 📈 Outcome ✔️ 100% test cases passed ✔️ Optimal time complexity: O(log n) ✔️ Clean execution without overthinking Building this discipline every day. Small wins → Big growth 💪 #BinarySearch #DataStructures #ProblemSolving #LeetCode #CodingJourney #TechGrowth #Consistency #LearningInPublic
Binary Search LeetCode Problem 704 Solution with 100% Test Cases Passing
More Relevant Posts
-
Day#16 🚀 Solved: LeetCode 186 – Reverse Words in a String II | In-Place Two-Pointer: A great follow-up to the classic reverse words problem — but with a twist: 🔹 Problem: Given a character array s, reverse the order of words in-place. 👉 No extra array allowed 👉 Words are separated by single spaces 👉 Input is a char array, not a string 💡 Key Intuition – Reverse Twice “Reverse the whole string, then reverse each word.” 🔄 Process: Reverse entire array Traverse and identify each word Reverse each word individually 🔹 Pseudo Code: function reverseWords(s): reverse(s, 0, n-1) start = 0 for i from 0 to n: if i == n or s[i] == ' ': reverse(s, start, i-1) start = i + 1 🔍 Example: Input: ["t","h","e"," ","s","k","y"] Step 1 → Reverse whole array 👉 "yks eht" Step 2 → Reverse each word 👉 "sky the" 💡 Why this works: • First reversal fixes word order • Second reversal fixes character order • No extra memory needed ⏱️ Complexity: • Time → O(n) • Space → O(1) ✅ 📌 Why Two Pointers? • Needed to reverse segments efficiently • Avoids extra memory usage • Enables in-place transformation 🧠 What I learned: • In-place problems require thinking in transformations • Two-pointer technique is extremely powerful for arrays/strings • Breaking problems into steps simplifies complex constraints • Small variations in problems can change the entire approach 🔁 Key takeaway: 👉 “Reverse globally, then fix locally.” #LeetCode #Strings #TwoPointers #Algorithms #DataStructures #SoftwareEngineering #CodingInterview #ProblemSolving #SDE
To view or add a comment, sign in
-
Day#3 🚀 Solved: LeetCode 408 – Valid Word Abbreviation | Two-Pointer Approach Sometimes even a small string problem teaches big lessons about careful parsing and pointer logic. 🔹 Problem: Given a word and its abbreviation, determine if the abbreviation is valid. Example: word = "internationalization", abbr = "i12iz4n" → True Rules: • Numbers in the abbreviation indicate how many characters are skipped • Leading zeros are not allowed • Letters must match exactly 💡 Key Idea – Two Pointers • Use i for the word and j for the abbreviation • Traverse the abbreviation: If it’s a letter, it must match the word at i If it’s a number, convert it to an integer and skip that many characters Reject numbers with leading zeros • Valid if both pointers reach the end of their strings ⏱️ Complexity: • Time: O(n + m) • Space: O(1) 🧠 What I learned: Two-pointer techniques are versatile for string pattern problems Edge cases matter: leading zeros, empty strings, or mismatched characters Parsing and skipping carefully is often cleaner than building intermediate strings 🔁 Revisiting these “medium” problems strengthens fundamentals and highlights reusable patterns for larger system challenges. #LeetCode #SoftwareEngineering #CodingInterview #Algorithms #DataStructures #ProblemSolving #SDE
To view or add a comment, sign in
-
Day 97/100 – #100DaysOfLeetCode 🚀 🧩 Problem: LeetCode 456 – 132 Pattern(Medium) 🧠 Approach: Traverse the array from right to left while maintaining a stack. Use a variable to track the “middle” element (the ‘2’ in 132 pattern) and check if a valid pattern exists. 💻 Solution: class Solution: def find132pattern(self, nums: List[int]) -> bool: stack = [] third = float('-inf') for i in range(len(nums) - 1, -1, -1): if nums[i] < third: return True while stack and nums[i] > stack[-1]: third = stack.pop() stack.append(nums[i]) return False ⏱ Time | Space: O(n) | O(n) 📌 Key Takeaway: Using a monotonic stack while iterating backwards helps efficiently detect complex patterns in linear time. #leetcode #dsa #development #problemSolving #CodingChallenge
To view or add a comment, sign in
-
-
🚀 Day 12 — Majority Element Continuing my journey of improving problem-solving skills with consistency and discipline — one problem every day. Today’s challenge introduced a clever algorithm that simplifies what initially looks like a counting problem. 🧩 Problem Solved: • Majority Element (LeetCode #169) 📚 Topic: Arrays + Boyer-Moore Voting Algorithm 💡 Key Insight: Instead of counting frequencies, we can cancel out different elements — and the majority element will always remain in the end. ⚡ Approach: • Initialize count = 0 and candidate = None • Traverse the array • If count == 0 → update candidate • If current element == candidate → increment count • Else → decrement count • Final candidate is the majority element 🎯 Takeaway: Sometimes the most efficient solutions come from smart observations, not brute force. ⏱ Complexity: • Time → O(n) • Space → O(1) 💻 Example: Input → [3,2,3] → Output → 3 Input → [2,2,1,1,1,2,2] → Output → 2 Smart thinking beats brute force every time 🚀 #ProblemSolving #LeetCode #Arrays #Algorithms #CodingJourney #100DaysOfCode #Consistency
To view or add a comment, sign in
-
-
Day#18 🚀 Solved: LeetCode 141 – Linked List Cycle | Fast & Slow Pointer Detecting cycles in a linked list is a classic problem — elegantly solved with two pointers: 👉 Must detect without modifying the list and ideally in O(1) space 🔹 Problem: Given the head of a singly linked list, determine if the list has a cycle. Return true if a cycle exists, else false Cannot modify the nodes 💡 Key Intuition – Fast & Slow Pointer (Floyd’s Tortoise & Hare) “Move one pointer twice as fast as the other. If a cycle exists, fast will eventually meet slow.” 🔄 Process: Initialize slow = head, fast = head Move slow 1 step at a time Move fast 2 steps at a time If fast meets slow → cycle exists If fast reaches null → no cycle 🔹 Pseudo Code: function hasCycle(head): slow = head fast = head while fast != null AND fast.next != null: slow = slow.next fast = fast.next.next if slow == fast: return true return false 🔍 Example: Input: 3 → 2 → 0 → -4 → back to 2 slow moves 1 step, fast moves 2 steps After a few iterations → slow = fast → cycle detected ✅ Input: 1 → 2 → 3 → null fast reaches null → no cycle ❌ 💡 Why this works: • Fast moves 2× → if there’s a cycle, it will eventually lap slow • Constant space → O(1) • Elegant and deterministic solution ⏱️ Complexity: • Time → O(n) ✅ • Space → O(1) ✅ 📌 Why Two Pointers? • Perfect for linked lists & sequences • Avoids extra memory like hash sets • Detects cycles in one pass 🧠 What I learned: • Fast & slow pointer technique is generalizable to other sequence problems (like Happy Numbers) • Key idea: difference in speeds ensures meeting inside cycles • Elegant solutions often combine simple pointers + math reasoning 🔁 Key takeaway: 👉 “Move fast, detect slow — cycles cannot hide.” #LeetCode #LinkedList #TwoPointers #Algorithms #DataStructures #SoftwareEngineering #CodingInterview #ProblemSolving #SDE
To view or add a comment, sign in
-
Moving Beyond Brute Force: Optimizing Sum of Distances 🚀 In software engineering, writing code that works is only the first step. Writing code that scales is where the real challenge lies. I recently tackled LeetCode 2615 (Sum of Distances), and it’s a perfect example of why understanding time complexity is crucial for a developer. The Problem: Given an array, for each element, calculate the sum of absolute differences ∣i−j∣ ∣i−j∣ for all other indices j j where the values are identical.The Developer’s Approach: 1️⃣ Identify the Bottleneck: A naive nested loop ( O(n2) O(n2 ) ) would attempt billions of operations for an input size of 105 105 , leading to a Time Limit Exceeded (TLE) error. We need an O(n) O(n) solution.2️⃣ Data Grouping: Use a HashMap to group indices of the same value. This narrows our focus only to relevant elements. 3️⃣ The Math Pivot (Prefix Sums): Instead of re-calculating distances for every index, we use mathematics. The total distance for any index can be split into: Left Side: (count_of_elements_on_left * current_index) - (sum_of_left_indices) Right Side: (sum_of_right_indices) - (count_of_elements_on_right * current_index) The Result: By maintaining a running prefix sum while iterating through the grouped indices, we transform a complex quadratic problem into a linear one. Key Takeaway: When you see "sum of absolute differences" in an array, think Prefix Sums. It’s one of the most powerful tools in a developer’s arsenal to turn inefficient logic into high-performance code. How do you approach optimization when you hit a performance wall? Let’s discuss in the comments! 💻✨ #SoftwareEngineering #Coding #Algorithms #Optimization #LeetCode #ProblemSolving #DeveloperMindset #CleanCode
To view or add a comment, sign in
-
Day 40 – Staying Consistent 🚀 🧠 DSA – (Linked List): Reverse Linked List Detect Cycle ⚛️ Development: Pagination API Filtering + Sorting Backend 💻 Machine Coding: Data Table with Pagination + Sorting Now building interview-level features. #50DaysOfCode
To view or add a comment, sign in
-
🚀 Day 97 of 100 Days of DSA 📌 LeetCode #96 (Unique Binary Search Trees) 📈 "Consistency over motivation, Progress over perfection" A classic Dynamic Programming problem that introduces the concept of Catalan Numbers. 🧩 Problem Statement Given an integer n: Count the number of structurally unique BSTs that can be formed using values from 1 to n 🧠 Thought Process At first: Try constructing all possible BSTs But quickly: - Number of trees grows rapidly - Explicit construction becomes inefficient So the focus shifts to: Counting instead of constructing 🚫 Brute Force Approach 1. Try all possible ways to build BSTs 2. For each root: • Recursively build left and right subtrees Problems: • Repeated subproblems • Huge recursion tree Time Complexity → Exponential ❌ 🔍 Key Insight Pick any number i as root: Left subtree → values [1 … i-1] Right subtree → values [i+1 … n] Number of BSTs: left_subtrees × right_subtrees 💡 Recurrence Relation Let: dp[n] = number of unique BSTs with n nodes Then: For each root i: dp[n] += dp[i - 1] * dp[n - i] ✅ Approach Used Dynamic Programming (Catalan Pattern) ⚙️ Strategy 1. Base cases: • dp[0] = 1 (empty tree) • dp[1] = 1 2. For each number of nodes: • Try every possible root • Combine left & right subtree counts 3. Build solution bottom-up 💡 Intuition Instead of building trees: Count how many ways left and right can be formed Then combine them. This transforms a structural problem into a counting problem. ⏱ Complexity Analysis Time Complexity: O(n²) Space Complexity: O(n) 💡 Key Learnings - Breaking problem into left & right subtrees simplifies logic - Recursive problems often hide DP patterns - This is a classic example of Catalan numbers - Counting problems are often easier than constructing solutions #100DaysOfDSA #Day97 #LeetCode #DynamicProgramming #BST #Catalan #Algorithms #DSA #CodingJourney
To view or add a comment, sign in
-
-
Every morning for months, I'd reopen Claude Code and re-explain everything. What project. What we decided yesterday. What broke. It felt like onboarding a new hire, daily. So I built a 5-layer memory system to stop the bleeding. Layer 1 is CLAUDE.md. Rules engine. Auto-loaded every session, contains a task router that forces the right agents and gates to activate. Layer 2 is primer.md. Rewritten at session end. Handoff note between yesterday-me and today-me. Layer 3 is memory.sh. A shell hook that injects live context on startup: git state, recent decisions, behavioral rules. Layer 4 is a hindsight module. Python script that extracts behavioral patterns from session transcripts. Changes how Claude responds, not just what it retrieves. Layer 5 is lossless-cc. Every message across every session logged to SQLite with sub-100ms search. 60K+ messages, 109+ sessions. Open-sourced it a few weeks ago. Worked beautifully. Until it didn't. Last week I audited the memory files themselves. 139 files. 53 weren't linked from the index. One piece of strategic guidance listed three ideas that were all killed months ago. Another entry contradicted a decision I'd made two weeks earlier, and Claude was still acting on the old version. The system was compounding all right. But 38% of what it had accumulated was silently out of date. Turns out I wasn't the only one hitting this. Andrej Karpathy posted about it recently as part of his LLM Wiki pattern. He runs a "lint pass" on his knowledge base to catch contradictions, orphans, and gaps. I stole the idea. Adapted it as Layer 6. The lint pass runs six checks biweekly. Orphan files. Dangling pointers. Duplicates. Contradictions. Stale references. Missing structure. First run dropped drift from 38% to 10%. Compound memory only compounds if the entries still match reality. Otherwise you've built an expensive way to remember lies. Dropping the lint skill as a gist below. It plugs into any file-based memory system, not just mine. How do you keep your AI from acting on outdated assumptions? Or have you accepted that it will? #AIMemory #ContextEngineering #ClaudeCode #DeveloperTools #BuildInPublic
To view or add a comment, sign in
Explore related topics
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