🚀 Day 4 — Reverse Integer Continuing my journey of improving problem-solving skills with consistency and discipline — one problem every day. Today’s challenge was not just about reversing digits, but handling constraints smartly. 🧩 Problem Solved: • Reverse Integer (LeetCode #7) 📚 Topic: Math + Edge Case Handling 💡 Key Insight: Reversing a number is easy — but ensuring the result stays within the 32-bit integer range is the real challenge. ⚡ Approach: • Identify the sign of the number • Convert number to absolute value • Extract digits using % 10 • Build reversed number step by step • Check for overflow before updating • Reapply the original sign 🎯 Takeaway: Writing code that works is good — writing code that handles edge cases is better. ⏱ Complexity: • Time → O(log n) • Space → O(1) 💻 Example: Input → 123 → Output → 321 Input → -123 → Output → -321 Input → 120 → Output → 21 Consistency builds confidence 🚀 #ProblemSolving #LeetCode #CodingJourney #100DaysOfCode #Consistency #LearningInPublic
Reversing Integers with Edge Case Handling
More Relevant Posts
-
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
-
🚀 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
To view or add a comment, sign in
-
-
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 37/75: Root-to-Leaf Logic In coding, as in life, we often have to explore different paths to see which one leads to our target. Today’s problem, "Path Sum," is a classic exercise in exactly that. Using Recursion, I built a solution that explores every branch of a Binary Tree until it finds a path that hits the exact target sum. It’s a great reminder that even when a structure looks complex, a consistent, step-by-step approach will eventually find the right way through. The Stats: 📅 37 Days of consecutive coding. ⚡ 100% Beats Runtime (0ms) — Performance is key! 🎯 Focus: Tree Traversals & Base Case Logic. The second month of this challenge is providing some of the most interesting logic puzzles yet. Staying focused and keeping the streak alive! 💻🔥 #Consistency #100DaysOfCode #Algorithms #JavaDeveloper #TechGrowth #ProblemSolving #LeetCodeChallenge #TreeTraversal
To view or add a comment, sign in
-
-
🚀 Day 8 of #LeetCodeDailyChallenge Some problems are not about logic alone… but handling messy real-world input 😵💫 📌 Today’s problem: String to Integer (atoi) 📍 Topic: Strings / Parsing ⚡ Difficulty: Medium What I learned today: 🔹 Ignoring leading whitespaces correctly 🔹 Handling signs (+ / -) carefully 🔹 Converting characters to digits step-by-step 🔹 Stopping at invalid characters (important edge case!) 🔹 Handling overflow within 32-bit integer range At first, it felt like simple conversion… But managing all edge cases together made it challenging 🤯 This problem reminded me: 👉 Real-world data is messy — code should handle it 👉 Edge cases + conditions = actual problem-solving Slowly improving not just coding… but handling complexity 🔥 #DSA #LeetCode #Strings #Parsing #ProblemSolving #LearningInPublic #Consistency #KeepGoing
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
-
Just solved today’s LeetCode Daily: “Minimum Operations to Make a Uni-Value Grid” At first glance, it looks like a simple grid problem but the real trick is spotting the math and pattern behind it Key Insights: - You can only add or subtract x so all elements must have the same remainder mod x otherwise it's impossible - Convert 2D grid to 1D array for easier processing - The optimal target value is the median not the mean - Median minimizes total absolute operations Approach: 1. Flatten the grid 2. Check feasibility using modulo 3. Sort the array 4. Pick median 5. Count operations using distance divided by x Clean Rust implementation below impl Solution { pub fn min_operations(grid: Vec<Vec<i32>>, x: i32) -> i32 { let rows = grid.len(); let cols = grid[0].len(); let mut array: Vec<i32> = Vec::new(); let mut ans = 0; let rem = grid[0][0] % x; let n = rows * cols; let mid_index = n / 2; for row in 0..rows { for col in 0..cols { if grid[row][col] % x != rem { return -1; } array.push(grid[row][col]) } } array.sort(); let median = array[mid_index]; for val in array { ans += (val - median).abs() / x; } ans } } What I like about this problem: It’s not about brute force it’s about thinking in transformations and choosing the right mathematical anchor median This is why solving problems in Rust feels clean and structured Key Insight: When minimizing sum of absolute differences always think median Drop your intuition, thoughts, or improvements in comments #LeetCode #RustLang #DSA #ProblemSolving #CodingDaily #SoftwareEngineering #Algorithms
To view or add a comment, sign in
-
-
🚀 LeetCode Day Problem Solving 🚀 Day-45 📌 Problem: Given an array nums[], find a good tuple (i, j, k) such that: ✔ nums[i] == nums[j] == nums[k] ✔ i < j < k 👉 Distance of tuple = |i - j| + |j - k| + |k - i| 🎯 Return the minimum possible distance among all such tuples ❌ If no valid tuple exists → return -1 🧠 Example: Input: nums = [1,2,1,1,3] ✅ Output: 6 📖 Explanation: Tuple → (0, 2, 3) Distance = 2 + 1 + 3 = 6 💡 Key Insight: ✔ For same values, indices matter ✔ Distance simplifies to: 👉 2 * (k - i) (since i < j < k) ✔ So we just need: 👉 Closest 3 indices of same number ⚡ Optimized Approach: ✔ Use HashMap / Array of lists to store indices ✔ For each value: 👉 Traverse indices and check every consecutive triplet 📊 Complexity Analysis: ⏱ Time Complexity: O(n) 📦 Space Complexity: O(n) 🧠 What I Learned: ✔ Pattern observation simplifies formula ✔ Grouping indices using hashmap ✔ Optimization by avoiding brute force O(n³) ✅ Day 45 Completed 🚀 Leveling up in Arrays + Optimization + Math Tricks 💪 #Leetcode #DSA #ProblemSolving #BitManipulation #CodingJourney #InterviewPreparation #Consistency #MilanSahoo 🚀
To view or add a comment, sign in
-
-
🚀 LeetCode Day Problem Solving 🚀 Day-44 📌 Problem: You are given an integer array nums. A tuple (i, j, k) is called good if: ✔ i, j, k are distinct ✔ nums[i] == nums[j] == nums[k] 👉 Distance of a good tuple: |i - j| + |j - k| + |k - i| 🎯 Goal: Find the minimum possible distance among all good tuples. If none exist → return -1. 🧠 Example: Input: nums = [1,2,1,1,3] ✅ Output: 6 📖 Explanation: Good tuple → (0,2,3) Distance = 2 + 1 + 3 = 6 💡 Key Insight: ✔ For same values, we only care about indices ✔ Sort indices for each number ✔ Try triplets of closest indices 👉 Important formula simplification: For sorted i < j < k Distance = (j-i) + (k-j) + (k-i) = 2*(k - i) ✔ So minimize → difference between farthest indices ⚡ Approach: ✔ Group indices by value (HashMap) ✔ For each value: - If size ≥ 3 → check consecutive triplets - Compute minimum distance 📊 Complexity Analysis: ⏱ Time Complexity: O(n) 📦 Space Complexity: O(n) 🧠 What I Learned: ✔ Grouping using HashMap ✔ Optimizing triplet computation ✔ Using math to simplify distance formula ✅ Day 44 Completed 🚀 Leveling up in Arrays + Hashing + Optimization 💪 #Leetcode #DSA #ProblemSolving #BitManipulation #CodingJourney #InterviewPreparation #Consistency #MilanSahoo 🚀
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