🚀 LeetCode — Problem 8 | Day 13 💡 Problem: String to Integer (atoi) --- 🧠 Problem: Convert a string into a 32-bit signed integer (like C/C++ atoi). --- 🧠 Approach: - Skip leading whitespaces - Check sign (+ / -) - Convert digits one by one - Stop at first non-digit character - Handle overflow before it happens --- ⚙️ Core Logic: - Build number step-by-step: result = result * 10 + digit - Before adding digit, check: • If result > Integer.MAX_VALUE / 10 • Or result == MAX/10 and digit > 7 👉 Return: - Integer.MAX_VALUE (overflow) - Integer.MIN_VALUE (underflow) --- ⏱ Time Complexity: O(n) 📦 Space Complexity: O(1) --- ⚠️ Edge Cases: - " 42" → leading spaces - "-42" → negative number - "42abc" → stop at non-digit - "abc" → no digits → return 0 - Large values → handled overflow --- 🔍 Insight: Careful parsing is more important than complex logic --- 🔑 Key Learning: - Step-by-step string parsing - Handling edge cases cleanly - Preventing overflow before it occurs - Real-world input validation logic --- #LeetCode #DSA #Java #CodingJourney
Convert String to 32-bit Signed Integer (atoi)
More Relevant Posts
-
Day 68/100 | #100DaysOfDSA 🧩🚀 Today’s problem: Add Two Numbers A fundamental linked list problem that mimics real-life addition. Problem idea: Add two numbers represented by linked lists (digits stored in reverse order). Key idea: Linked list traversal + carry handling. Why? • We process digits one by one (like manual addition) • Need to handle carry at each step • Lists can have different lengths How it works: • Use a dummy node to build the result • Traverse both lists simultaneously • Add values + carry • Create new node with (sum % 10) • Update carry = sum / 10 • Move pointers forward • Continue until both lists and carry are done Time Complexity: O(max(m, n)) Space Complexity: O(max(m, n)) Big takeaway: Using a dummy node simplifies linked list construction and avoids edge cases. This pattern is very common in linked list problems. 🔥 Day 68 done. 🚀 #100DaysOfCode #LeetCode #DSA #Algorithms #LinkedList #Java #CodingJourney #ProblemSolving #InterviewPrep #TechCommunity
To view or add a comment, sign in
-
-
💡 LeetCode 191 — Number of 1 Bits (Hamming Weight) Recently solved an interesting bit manipulation problem that highlights the power of low-level optimization 🚀 🔍 Problem Statement: Given an unsigned integer, count the number of set bits (1s) in its binary representation. 🧠 Key Insight: Instead of checking every bit individually, we can use a clever trick: 👉 n & (n - 1) removes the rightmost set bit in each operation. This allows us to count only the set bits, making the solution more efficient. ⚙️ Approach Used (Brian Kernighan’s Algorithm): Initialize a counter Repeatedly apply n = n & (n - 1) Increment count until n becomes 0 📈 Time Complexity: O(k), where k = number of set bits (faster than checking all 32 bits) 📦 Space Complexity: O(1) ✨ Why this problem is important: Strengthens understanding of bit manipulation Frequently asked in interviews Useful in low-level optimization and system design 💬 Takeaway: Sometimes the best solutions come from understanding how data is represented at the binary level. Small tricks can lead to big optimizations! #LeetCode #DSA #CodingInterview #Java #BitManipulation #ProblemSolving #TechJourney
To view or add a comment, sign in
-
-
Day 67/100 | #100DaysOfDSA 🧩🚀 Today’s problem: Subsets II Another classic backtracking problem with a twist (duplicates). Problem idea: Generate all possible subsets (power set), but avoid duplicate subsets. Key idea: Backtracking + sorting to handle duplicates. Why? • We need to explore all subset combinations • Duplicates in input can lead to duplicate subsets • Sorting helps us skip repeated elements efficiently How it works: • Sort the array first • At each step, add current subset to result • Iterate through elements • Skip duplicates using condition: 👉 if (i > start && nums[i] == nums[i-1]) continue • Choose → recurse → backtrack Time Complexity: O(2^n) Space Complexity: O(n) recursion depth Big takeaway: Handling duplicates in backtracking requires careful skipping logic, not extra data structures. This pattern appears in many problems (subsets, permutations, combinations). 🔥 Day 67 done. 🚀 #100DaysOfCode #LeetCode #DSA #Algorithms #Backtracking #Recursion #Java #CodingJourney #ProblemSolving #InterviewPrep #TechCommunity
To view or add a comment, sign in
-
-
🚀 Day 78 — Slow & Fast Pointer Pattern (Complete Revision) Today I wrapped up my revision of the Slow & Fast Pointer pattern — one of the most versatile techniques in DSA. This single pattern solves ~60% of linked list problems and extends beautifully to arrays, strings, and even mathematical sequences. 📌 Three Core Applications (100% guaranteed): 1️⃣ Detecting a Cycle slow moves 1 step, fast moves 2 steps. If they meet → cycle exists. If fast reaches null → no cycle. 2️⃣ Finding the Cycle’s Starting Point Detect cycle first (slow == fast). Reset slow to start, keep fast at meeting point. Move both 1 step at a time → they meet at cycle start. 3️⃣ Finding the Middle of a Linked List slow moves 1 step, fast moves 2 steps. When fast reaches end → slow is at middle. 🧠 Beyond Linked Lists: This pattern also solves: LeetCode 202 – Happy Number (mathematical cycle) LeetCode 287 – Find Duplicate Number (array as linked list) LeetCode 141/142 – Linked List Cycle I & II LeetCode 876 – Middle of Linked List 💡 Critical Safety Check: Always ensure fast != null && fast.next != null before moving fast.next.next — avoids null pointer exceptions. No guilt about past breaks. Patterns > problems. One pattern at a time, one day at a time. #DSA #SlowFastPointer #CycleDetection #LinkedList #CodingJourney #Revision #Java #ProblemSolving #Consistency #GrowthMindset #TechCommunity #LearningInPublic
To view or add a comment, sign in
-
🚀 #100DaysOfCode | Day 49 🔍 Solved: Largest Number Today I worked on an interesting problem where the goal was to arrange numbers such that they form the largest possible number. 💡 Key Insight: Instead of normal sorting, we compare numbers based on their string combinations (like "ab" vs "ba"). 📌 Approach: ✔ Converted integers to strings ✔ Used a custom comparator for sorting ✔ Compared (a + b) and (b + a) ✔ Sorted in descending order based on best combination ✔ Handled edge case when all elements are 0 Why this works: By comparing two numbers in different orders, we ensure that the arrangement always produces the maximum possible value when concatenated. 🎯 What I Learned: This problem taught me that sorting can go beyond numbers—custom logic and string manipulation are powerful tools in problem solving. #Java #DSA #LeetCode #Sorting #Comparator #CodingJourney #ProblemSolving #TechSkills 🚀
To view or add a comment, sign in
-
-
🚀 LeetCode Challenge 34/50 💡 Approach: Column Compression + Prefix Sum + TreeSet A true multi-technique Hard problem! Compress 2D matrix into 1D row sums, then use a TreeSet with prefix sums to efficiently find the maximum subarray sum ≤ k! 🔍 Key Insight: → Fix left and right column boundaries (O(cols²)) → Compress rows between boundaries into temp[] array → Now the problem reduces to: max subarray sum ≤ k in 1D! → Use prefix sum + TreeSet for O(n log n) per column pair → TreeSet.ceiling(prefixSum - k) finds the best previous prefix! 📈 Complexity: ❌ Brute Force → O(rows² × cols²) Time ✅ Compression + TreeSet → O(cols² × rows × log(rows)) Time This problem is a masterclass in problem reduction — turn 2D into 1D, then apply the right data structure. Three techniques, one elegant solution! 🎯 #LeetCode #DSA #TreeSet #PrefixSum #Java #ADA #PBL2 #LeetCodeChallenge #Day34of50 #CodingJourney #ComputerEngineering #AlgorithmDesign #HardLeetCode
To view or add a comment, sign in
-
-
🚀 LeetCode Challenge 19/50 💡 Approach: Horizontal Scanning The sorting-based approach costs O(S log n). Instead, I used Horizontal Scanning — take the first string as the prefix and keep shrinking it until every string agrees. No sorting, no extra space! 🔍 Key Insight: → Start with strs[0] as the full prefix candidate → For each next string, shrink prefix from the right until it matches → If prefix becomes empty at any point → return "" → What's left is the longest common prefix! 📈 Complexity: ❌ Sort-based → O(S log n) Time ✅ Horizontal Scan → O(S) Time, O(1) Space where S = total characters across all strings The smartest solutions don't always need fancy data structures — sometimes a simple shrinking window does the job perfectly! 🪟 #LeetCode #DSA #StringManipulation #Java #ADA #PBL2 #LeetCodeChallenge #Day19of50 #CodingJourney #ComputerEngineering #AlgorithmDesign #LongestCommonPrefix
To view or add a comment, sign in
-
-
🚀 Day 76 — Slow & Fast Pointer (Find the Duplicate Number) Continuing the cycle detection pattern — today I applied slow‑fast pointers to an array problem where the values act as pointers to indices. 📌 Problem Solved: - LeetCode 287 – Find the Duplicate Number 🧠 Key Learnings: 1️⃣ The Problem Twist Given an array of length `n+1` containing integers from `1` to `n` (inclusive), with one duplicate. We must find the duplicate without modifying the array and using only O(1) extra space. 2️⃣ Why Slow‑Fast Pointer Works Here - Treat the array as a linked list where `i` points to `nums[i]`. - Because there’s a duplicate, two different indices point to the same value → a cycle exists in this implicit linked list. - The duplicate number is exactly the entry point of the cycle (same logic as LeetCode 142). 3️⃣ The Algorithm in Steps - Phase 1 (detect cycle): `slow = nums[slow]`, `fast = nums[nums[fast]]`. Wait for them to meet. - Phase 2 (find cycle start): Reset `slow = 0`, then move both one step at a time until they meet again. The meeting point is the duplicate. 4️⃣ Why Not Use Sorting or Hashing? - Sorting modifies the array (not allowed). - Hashing uses O(n) space (not allowed). - Slow‑fast pointer runs in O(n) time and O(1) space — perfect for the constraints. 💡 Takeaway: This problem beautifully demonstrates how the slow‑fast pattern transcends linked lists. Any structure where you can define a “next” function (here: `next(i) = nums[i]`) can be analyzed for cycles. Recognizing this abstraction is a superpower. No guilt about past breaks — just another pattern mastered, one day at a time. #DSA #SlowFastPointer #CycleDetection #FindDuplicateNumber #LeetCode #CodingJourney #Revision #Java #ProblemSolving #Consistency #GrowthMindset #TechCommunity #LearningInPublic
To view or add a comment, sign in
-
𝐃𝐚𝐲 𝟓𝟕 – 𝐃𝐒𝐀 𝐉𝐨𝐮𝐫𝐧𝐞𝐲 | 𝐀𝐫𝐫𝐚𝐲𝐬 🚀 Today’s problem focused on finding the maximum gap between consecutive elements in sorted order — without actually sorting. 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 𝐒𝐨𝐥𝐯𝐞𝐝 • Maximum Gap 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡 – 𝐁𝐮𝐜𝐤𝐞𝐭 𝐒𝐨𝐫𝐭 𝐈𝐝𝐞𝐚 • Found global minimum and maximum • Calculated minimum possible gap using: gap = ceil((max − min) / (n − 1)) • Created buckets to store min and max values • Placed elements into buckets based on their range • Final answer comes from the gap between buckets, not inside them 𝐊𝐞𝐲 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠𝐬 • Sorting is not always required to find ordered differences • Bucket strategy helps achieve linear time • Maximum gap always lies between buckets, not within • Mathematical insights (pigeonhole principle) guide optimization 𝐂𝐨𝐦𝐩𝐥𝐞𝐱𝐢𝐭𝐲 • Time: O(n) • Space: O(n) 𝐓𝐚𝐤𝐞𝐚𝐰𝐚𝐲 Sometimes the problem is not about sorting — but about understanding how elements are distributed. 57 days consistent 🚀 On to Day 58. #DSA #Arrays #BucketSort #LeetCode #Java #ProblemSolving #DailyCoding #LearningInPublic #SoftwareDeveloper
To view or add a comment, sign in
-
-
🚀 Day 77 — Slow & Fast Pointer (Middle of the Linked List) Another day, another clean application of the slow‑fast pointer pattern — this time without cycle detection, just finding the midpoint efficiently. 📌 Problem Solved: - LeetCode 876 – Middle of the Linked List 🧠 Key Learnings: 1️⃣ The Problem Given the head of a singly linked list, return the middle node. If there are two middle nodes (even length), return the second one. 2️⃣ Why Slow‑Fast Pointer Works Here - `slow` moves 1 step at a time. - `fast` moves 2 steps at a time. - When `fast` reaches the end (or `fast.next == null`), `slow` is exactly at the middle. - For even length, `fast` ends at `null` → `slow` points to the second middle node (perfect for this problem’s requirement). 3️⃣ The Code (Simple & Elegant) while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; } return slow; 4️⃣ Why Not Just Count Then Traverse? - Brute force: count nodes → traverse again → O(n) but two passes. - Slow‑fast pointer achieves the same in one pass with O(1) extra space. 💡 Takeaway: Slow‑fast pointer isn’t only for cycle detection. It’s a versatile tool for: - Finding middle (this problem) - Detecting cycles (LeetCode 141/142) - Finding duplicate numbers (LeetCode 287) - Happy number detection (LeetCode 202) Each problem adds a new dimension to understanding the same pattern. No guilt about past breaks — just showing up, solving, and growing. #DSA #SlowFastPointer #MiddleOfLinkedList #LeetCode #CodingJourney #Revision #Java #ProblemSolving #Consistency #GrowthMindset #TechCommunity #LearningInPublic
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