🚀 Day 8 of #120DaysOfCode — String to Integer (atoi) 🧩 Today’s challenge was LeetCode Problem 8: “String to Integer (atoi)”, a classic string parsing problem that teaches how to handle input conversion safely and efficiently — something we often take for granted in programming. 🧠 Problem Summary: We need to implement the myAtoi(string s) function that converts a string into a 32-bit signed integer. The function must: Ignore leading whitespaces Handle optional + or - signs Extract the number until a non-digit is found Clamp (limit) the value within the 32-bit integer range Return the final integer result 📘 Example: Input → " -042" Output → -42 ⚙️ Approach I Used: I solved this problem using a step-by-step parsing approach: Trim spaces: Move through the string to skip leading whitespaces. Check the sign: If the next character is '-', mark the sign as negative, otherwise positive. Convert characters to digits: Loop through the characters while they are digits and build the result (result = result * 10 + digit). Handle overflow: Before updating the result, check if adding another digit would exceed the 32-bit integer range ([-2³¹, 2³¹ - 1]). Return the final value: Apply the sign and return the integer. This approach ensures correctness, prevents overflow, and follows a clean linear-time logic with O(n) complexity and O(1) space. 💡 Key Learning: Even a simple-looking task like string-to-integer conversion involves careful consideration of edge cases, boundaries, and input validation — all critical in real-world software systems. 💬 Next Goal: Continue improving my problem-solving skills with more logic-building and string manipulation challenges! #100DaysOfCode #120DaysOfCode #LeetCode #CProgramming #ProblemSolving #CodingChallenge #DeveloperJourney #LearningEveryday
Solved LeetCode Problem 8: String to Integer (atoi)
More Relevant Posts
-
🚀 LeetCode Daily Challenge — 3726. Remove Zeros in Decimal Representation (Easy) Ever thought how a simple number like 1020030 can turn into 123? 🤔 That’s the power of string manipulation in programming — short, clean, and efficient! 💡 🧩 Problem Summary: You’re given a positive integer n. Your task: Remove all zeros from its decimal representation. Example: Input: n = 1020030 Output: 123 ✅ Hint: Convert the number to a string → remove all '0' → convert back to integer. That’s it — one-liner solution for clean data transformation. 🔥 💻 I’ve explained this problem with step-by-step approaches and code on my website 👉 algopush.com Check it out for brute force to optimized explanations! #LeetCode #LeetCodeChallenge #Coding #ProblemSolving #DSA #Programming #100DaysOfCode #CodeSeCareer #TechLearning #Developers #algopush #LeetCodeDaily #StringManipulation #LearnToCode #erdelhiboy #leetcodeeasy
To view or add a comment, sign in
-
-
🥷 Day 164 of My 365 LeetCode Challenge is done! 💥 Kicked off strong, solved my problem, and the coding vibe is awesome! 🧠 💡 LeetCode 1625 — Lexicographically Smallest String After Applying Operations Today’s challenge was an interesting blend of string manipulation, BFS traversal, and modular arithmetic — the kind of problem that truly sharpens both your algorithmic thinking and pattern recognition skills. 🧠✨ We’re given a numeric string s and two integers a and b. Two operations can be performed repeatedly in any order: 1️⃣ Add a to all digits at odd indices (with digits wrapping around modulo 10). 2️⃣ Rotate the string to the right by b positions. The goal? 🔍 Find the lexicographically smallest string possible after performing any number of these operations. Sounds simple, right? But here’s the catch — since operations can be performed infinitely, the problem hides a state-space exploration challenge. The same string can appear multiple times via different paths, so blindly iterating could easily lead to infinite loops or redundant computations. ⚙️ Approach & Thought Process: To systematically explore all possible transformations, I used Breadth-First Search (BFS) — perfect for enumerating all reachable states in minimal steps. 🔸 Step 1: Start from the original string and push it into a queue. 🔸 Step 2: For each string, perform both allowed operations: - Add a to digits at odd indices (handling digit wraparound using (digit + a) % 10). - Rotate the string by b positions. 🔸 Step 3: Use a set to track all previously visited strings to prevent cycles. 🔸 Step 4: Continuously compare and update the smallest lexicographic string seen so far. Once the queue is exhausted, the smallest recorded string is our answer ✅ 🔥 Key Learning: This problem elegantly demonstrates how graph traversal (BFS) can be applied beyond traditional graphs — even on state transformations of strings. Recognizing this pattern is a huge step toward mastering advanced algorithmic thinking. ✨ Every problem like this one is a reminder that great coding isn’t about memorizing — it’s about seeing structure where others see chaos. #LeetCode #CPlusPlus #CodingChallenge #ProblemSolving #Algorithms #BFS #SoftwareEngineering #Programming #LearningJourney #CodeNewbie #DataStructures
To view or add a comment, sign in
-
-
Tackling a Quick LeetCode Challenge: Final Value of Variable After Performing Operations (2011) It's amazing how a simple iteration can solve a coding problem! This one is a perfect example of keeping it simple: tracking a variable's state change based on a list of defined operations. The Problem: We start with x=0 and are given an array of string operations (like ++X, X++, --X, X--). We need to calculate the final value of x. My C++ Approach: I noticed that regardless of whether the increment/decrement is pre (++X, −−X) or post (X++, X−−), the effect is the same for the final value. Therefore, I only need to check what the operation is, not where the X is. I iterate through the operations array. Inside the loop, I check if the string contains two plus signs ("++"). An even simpler check, as shown in the code, is checking if the operation string equals "++X" or "X++" or even just checking for the presence of a '+'. If it's an increment operation, I use x++. If it's a decrement operation, I use x--. A neat little problem to practice basic array iteration and conditionals! Full code is accepted and running in the screenshot. Have you solved this one? What was your approach? #DataStructures #Algorithms #CodingInterviewPrep #SoftwareDevelopment #DailyCoding #C++
To view or add a comment, sign in
-
-
🚀 How I Solved LeetCode’s Word Search Problem Without DFS or Recursion When I came across Word Search (LeetCode 79), I noticed that almost every solution used DFS and backtracking. But I wanted to solve it my own way — using index tracking and adjacency logic instead of recursion. My intuition was simple: If a word exists in the grid, every next letter must lie right next to the previous one — either up, down, left, or right. That means their coordinate difference should satisfy: abs(x1 - x2) + abs(y1 - y2) == 1. This small observation became the foundation of my entire approach. 💡 My Thought Process 1️⃣ I mapped every letter in the grid to its coordinates. 2️⃣ I started from all positions of the first letter in the word. 3️⃣ For every next letter, I checked which positions are adjacent and not already used. 4️⃣ I extended paths step by step — no recursion, only iteration. 5️⃣ If any path reached the last letter → the word exists. ⚙️ My Implementation I used a BFS-style iterative search, where each state holds: the current cell (x, y) the current index in the word and a bitmask representing already-used cells. This replaced recursion and heavy visited[][][] arrays with a compact integer mask. Each move just extended to adjacent cells if the next character matched. It handled tricky cases like "ABCB" perfectly → returned false, which even some DFS implementations fail on. ✅ Why It Worked ✔️ No recursion = no stack overflow. ✔️ Bitmask = minimal memory use. ✔️ Adjacency rule = exactly matches grid movement. ✔️ Iterative BFS = simple, efficient, and logical. 🎯 What I Learned You don’t always need to follow the standard algorithms. Sometimes, just trusting your intuition and building around your idea leads to something even better. This problem taught me that creativity and logic go hand in hand. And when you believe in your approach — it truly works. 💪 #Coding #LeetCode #ProblemSolving #Cplusplus #Innovation #DSA #Learning #DeveloperJourney
To view or add a comment, sign in
-
-
🚀 Day 17 of #100DaysofCode Challenge! 🚀 🔍 What is Dynamic Programming (DP), and why does it matter? I recently watched Aditya Verma’s introductory video on DP and here are the highlights: • DP is an optimization over naïve recursion — it’s about identifying when you’re solving the same sub-problem repeatedly, and instead reuse those results (overlapping sub-problems + optimal substructure). • The typical workflow: start with a recursive solution, notice repeated work → switch to memoization (top-down) → then possibly convert to tabulation (bottom-up). • The key mindset shift: Think in terms of subproblem states and transitions/choices — that’s what lets you build from smaller results to the full solution. • Use DP when brute force recursion is too slow and when the problem naturally splits into smaller pieces whose optimal solutions combine. • Base cases, initialization, and correct ordering (especially in bottom-up) are crucial — you can’t just “DP-ify” any recursion without thinking about these. #Day17 #DynamicProgramming #Algorithms #ProblemSolving #CodingMindset #SoftwareEngineering #AdityaVerma #CodingJourney
To view or add a comment, sign in
-
-
🚀 Day 7 of #120DaysOfCode Challenge 💡 Problem: Reverse Integer (LeetCode #7 | Medium) 📄 Problem Statement: Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes it to go outside the signed 32-bit integer range [-2³¹, 2³¹ - 1], then return 0. 🧩 My Approach: Extract the last digit of x using % 10. Build the reversed number step by step using rev = rev * 10 + digit. Carefully check for overflow before multiplying or adding — using INT_MAX and INT_MIN limits to ensure the reversed number stays valid. If overflow is detected, return 0. 🔍 Key Learnings: How to handle integer overflow without using 64-bit variables. Importance of edge case testing and boundary conditions. Reinforced understanding of modulus (%) and integer division (/) operations. 🔥 Progress: Day 7 / 120 📚 Language: C 🏁 Problem Solved: Reverse Integer (LeetCode #7) Every problem is a small step toward stronger logic and cleaner code! 💪 #100DaysOfCode #120DaysOfCode #CodingChallenge #LeetCode #CProgramming #ProblemSolving #LearnEveryday #BuildInPublic
To view or add a comment, sign in
-
-
💻 Day 3 of My #120DaysOfLeetCode Challenge 🚀 🧩 Problem: Longest Substring Without Repeating Characters Difficulty: Medium | Language Used: C 🔍 What’s the Problem About? The task is to find the length of the longest substring in a given string that contains no repeating characters. For example: Input: "abcabcbb" → Output: 3 (Longest substring: "abc") Input: "pwwkew" → Output: 3 (Longest substring: "wke") Input: "bbbbb" → Output: 1 (Longest substring: "b") This problem is a classic example of how we can optimize brute force logic using sliding window and two-pointer techniques. ⚙️ Approach I Used – Sliding Window Technique Instead of checking every possible substring (which would be very slow), I used a sliding window approach with two pointers (left and right) and a frequency array to track visited characters. Here’s the step-by-step thought process: Start both pointers at the beginning of the string. Move the right pointer one step at a time, adding characters to the window. If a character repeats, move the left pointer ahead until all characters in the window are unique again. Keep track of the maximum window size during the process. This ensures each character is processed only once → giving an efficient O(n) solution. 💡 Key Takeaways Learned how two-pointer and sliding window techniques can simplify substring problems. Understood how to use frequency arrays to track duplicates efficiently. Strengthened logical reasoning and window-based problem-solving skills in C. Every new problem is an opportunity to refine logic, enhance efficiency, and get one step closer to mastering Data Structures and Algorithms. Day 3 completed ✅ | 117 more to go 💪 #LeetCode #CProgramming #DSA #ProblemSolving #CodingChallenge #100DaysOfCode #LearningJourney #SlidingWindow
To view or add a comment, sign in
-
-
#digitaltechnology #code #logic #objectorientedprogramming #oop #reallife #ides #assembler #compiler #interpreters #action #calling #systems #stewardship #purpose Code is not just logic... it’s a dynamic fusion of logic, language, and design. While logic forms the backbone, enabling a program to make decisions and follow structured steps, coding also demands fluency in syntax, creativity in problem-solving, and clarity in communication. Developers must not only think algorithmically but also write readable, maintainable code that interacts with users, systems, and other developers. They navigate tools, frameworks, and evolving requirements, often balancing efficiency with elegance. In essence, coding is as much about crafting thoughtful, adaptable solutions as it is about executing logical instructions.
IS CODE JUST LOGIC?
https://www.youtube.com/
To view or add a comment, sign in
-
I’ve been using Cursor and Claude Code since the early days — and honestly, after a phase of disappointment with Cursor, I had completely shifted to Claude Code. But Cursor 2.0 hits differently. This update isn’t just a patch — it’s a complete transformation of how AI-assisted coding feels. Here’s what stood out to me: → Multi-Agents: Run up to 8 agents in parallel on isolated workspaces — no conflicts, no chaos. → Composer Model: Their new agent model is 4× faster — perfect for fast-paced dev loops. → Browser (GA): Agents can now interact directly with web pages — a game-changer for UI-driven automation. → Sandboxed Terminals: Secure command execution with zero network access — safer testing, fewer risks. → Team Commands: Create and share prompts, rules, and workflows across your team — a real productivity boost. → Improved LSPs: Much smoother experience in large Python and TypeScript projects. → Plan Mode: Build and compare multiple agent plans in the background — parallel thinking at its best. → Enterprise Suite: Audit logs, admin control, and compliance-ready security — finally enterprise-grade. Final thought: Cursor 2.0 feels mature — fast, stable, and deeply team-oriented. If you left Cursor before, this version might just win you back. #Cursor #Claude #AItools #Developers #AgenticAI #Coding #DevTools #Productivity
To view or add a comment, sign in
-
-
🚀 Day 19/50 | LeetCode Coding Challenge Today's problem: Maximum Frequency After Operations - A challenging medium-level problem that tested my optimization skills! 💡 The Challenge: Given an array and k operations, we can add values in range [-k, k] to selected indices. The goal? Maximize the frequency of any element. 🎯 Key Learnings: 1️⃣ Binary Search Optimization: Replaced O(n²) nested loops with binary search using lower_bound/upper_bound - reduced complexity from O(n²) to O(n log n) 2️⃣ Two-Pointer Technique: Implemented sliding window to efficiently find valid ranges where elements can be transformed 3️⃣ Integer Overflow Awareness: Used long long for calculations with values up to 10⁹ to prevent overflow errors 4️⃣ Multiple Strategies: Combined two approaches: Keeping existing values unchanged Transforming all elements to a new target value ⚡ The Result: ✅ 633/633 test cases passed ✅ Time complexity: O(n log n) ✅ Optimized from TLE to accepted solution 🔥 Biggest Takeaway: When you hit Time Limit Exceeded, don't give up! Analyze your bottlenecks: Identify nested loops → Consider binary search or two pointers Watch for repeated computations → Use preprocessing Always handle edge cases (overflow, boundary conditions) The journey from brute force to optimal solution taught me more than just getting it right the first time ever could. Day 19 ✅ | 31 more days to go 💪 Shishir chaurasiya and PrepInsta #100DaysOfCode #CodingChallenge #LeetCode #DSA #ProblemSolving #SoftwareEngineering #CPlusPlus #Algorithms #TechJourney #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