Day 2 of my #50DaysOfCode challenge Today, I tackled a problem that focuses on careful string parsing and numeric conversions String to Integer (atoi).It’s a great exercise that deepens understanding of data types, character operations, and overflow handling in Java. Problem: String to Integer (atoi) Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer. The algorithm for myAtoi(string s) is as follows: Ignore any leading whitespace (" "),Determine the sign by checking if the next character is '-' or '+', assuming positivity if neither present. Read the integer by skipping leading zeros until a non-digit character is encountered or the end of the string is reached. If no digits were read, then the result is 0. Solution: O(N) The solution iterates through each character of the string once. It first skips leading spaces, then checks for a sign, and builds the number digit by digit. At each step, it performs an overflow check to ensure the value stays within the 32-bit signed integer range. Finally, it multiplies the result by the sign and returns it as an integer. This efficient linear-time approach ensures both accuracy and robustness for different input formats.
Solved String to Integer (atoi) problem in Java
More Relevant Posts
-
Day 27 of #100DaysOfCode – LeetCode Problem #496: Next Greater Element I 🧩 Problem: Given two arrays nums1 and nums2, where nums1 is a subset of nums2, find the next greater element for each element of nums1 in nums2. If no greater element exists, return -1. 💡 Approach: Use a stack to track the next greater element for all numbers in nums2. Store results in a map for O(1) lookup when iterating nums1. This gives an efficient O(n) solution. 💻 Java Code: class Solution { public int[] nextGreaterElement(int[] nums1, int[] nums2) { Map<Integer, Integer> mpp = new HashMap<>(); Stack<Integer> st = new Stack<>(); for (int num : nums2) { while (!st.isEmpty() && st.peek() < num) { mpp.put(st.pop(), num); } st.push(num); } while (!st.isEmpty()) mpp.put(st.pop(), -1); int[] ans = new int[nums1.length]; for (int i = 0; i < nums1.length; i++) ans[i] = mpp.get(nums1[i]); return ans; } } ⏱️ Complexity: Time: O(nums1.length + nums2.length) Space: O(nums2.length) ✅ Result: Accepted (Runtime: 0 ms) This problem highlights how monotonic stacks can efficiently solve next-greater-element scenarios without nested loops.
To view or add a comment, sign in
-
🚀 Day 34 of #100DaysOfCode – LeetCode Problem #228: Summary Ranges 🧩 Problem: Given a sorted, unique integer array nums, return the smallest list of ranges that covers all numbers in the array exactly. Each range is represented as: "a->b" if the range covers more than one number. "a" if it covers a single number. 📘 Example: Input: nums = [0,1,2,4,5,7] Output: ["0->2", "4->5", "7"] 💡 Approach: We traverse the array while tracking the start of each range. Whenever we detect a break (i.e., the next number isn’t consecutive), we close the range and store it. 🔍 Steps: Initialize start = nums[0]. Traverse the array. If the next element isn’t consecutive, push "start->current" (or "start" if equal). Move to the next starting number and continue. 💻 Java Code: class Solution { public List<String> summaryRanges(int[] nums) { List<String> result = new ArrayList<>(); if (nums.length == 0) return result; int i = 0; while (i < nums.length) { int start = nums[i]; int j = i; while (j + 1 < nums.length && nums[j + 1] == nums[j] + 1) { j++; } if (start == nums[j]) { result.add(String.valueOf(start)); } else { result.add(start + "->" + nums[j]); } i = j + 1; } return result; } } ⏱️ Complexity: Time: O(n) Space: O(1) ✅ Result: Accepted (Runtime: 3 ms) It’s a simple yet elegant problem — a great reminder that clean logic often beats complex tricks
To view or add a comment, sign in
-
✅ Day 35 of #100DaysOfCode Challenge 📘 LeetCode Problem 112: Path Sum 🧩 Problem Statement: Given the root of a binary tree and an integer targetSum, return true if there exists a root-to-leaf path whose sum of node values equals targetSum. Example: Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22 Output: true Explanation: Path 5 → 4 → 11 → 2 gives the sum = 22 ✅ 💡 Simple Approach: If the tree is empty → return false If it’s a leaf node → check if its value equals targetSum Otherwise → subtract node value and check left and right recursively 💻 Easiest Java Code: class Solution { public boolean hasPathSum(TreeNode root, int sum) { if (root == null) return false; if (root.left == null && root.right == null && root.val == sum) return true; sum = sum - root.val; return hasPathSum(root.left, sum) || hasPathSum(root.right, sum); } } ⚙ Complexity: ⏱ Time: O(n) → visit each node once 💾 Space: O(h) → recursion stack (h = height of tree) 🌿 Small code, big concept — recursion makes trees easy 🌱 #Day35 #100DaysOfCode #LeetCode #Java #DSA #BinaryTree #Recursion #CodingChallenge
To view or add a comment, sign in
-
-
💻 Day 52 of #100DaysOfCodeChallenge Today’s problem: LeetCode 203 – Remove Linked List Elements 🧩 I worked on a Linked List manipulation problem where the goal is to remove all nodes that match a given value. This problem helped strengthen my understanding of pointer handling and dummy node usage in linked lists. 🧠 What I Learned: Handling edge cases where the head itself might need to be removed. Using a dummy node before the head to simplify pointer operations. How current and next pointers work together to modify a linked list safely. 🧩 Java Solution: class Solution { public ListNode removeElements(ListNode head, int val) { ListNode dummy = new ListNode(0); dummy.next = head; ListNode current = dummy; while (current.next != null) { if (current.next.val == val) current.next = current.next.next; else current = current.next; } return dummy.next; } } ⏱ Complexity: Time: O(n) Space: O(1) Every day, I’m getting more confident with data structures and linked list traversal logic. On to the next challenge 🚀 #Day52 #LeetCode #Java #100DaysOfCode #CodingChallenge #LinkedList #ProblemSolving
To view or add a comment, sign in
-
-
💻 Day 52 of #100DaysOfCodeChallenge Today’s problem: LeetCode 203 – Remove Linked List Elements 🧩 I worked on a Linked List manipulation problem where the goal is to remove all nodes that match a given value. This problem helped strengthen my understanding of pointer handling and dummy node usage in linked lists. 🧠 What I Learned: Handling edge cases where the head itself might need to be removed. Using a dummy node before the head to simplify pointer operations. How current and next pointers work together to modify a linked list safely. 🧩 Java Solution: class Solution { public ListNode removeElements(ListNode head, int val) { ListNode dummy = new ListNode(0); dummy.next = head; ListNode current = dummy; while (current.next != null) { if (current.next.val == val) current.next = current.next.next; else current = current.next; } return dummy.next; } } ⏱ Complexity: Time: O(n) Space: O(1) Every day, I’m getting more confident with data structures and linked list traversal logic. On to the next challenge 🚀 #Day52 #LeetCode #Java #100DaysOfCode #CodingChallenge #LinkedList #ProblemSolving
To view or add a comment, sign in
-
-
✨ Day 52 of 100: Copy List with Random Pointer ✨ Today’s challenge was LeetCode 138 – Copy List with Random Pointer 🧠 The task: Given a linked list where each node has two pointers — 🔹 next: points to the next node 🔹 random: points to any node in the list (or null) we need to create a deep copy of this list. 💡 Key Takeaways: 🔹 Learned how to handle complex data structures where nodes reference each other in non-linear ways. 🔹 Practiced creating a deep copy using HashMap to maintain the mapping between original and copied nodes. 🔹 Explored an optimized in-place approach — interleaving original and copied nodes to avoid extra space. 🔹 Strengthened understanding of pointer manipulation and object references in Java. 🚀 This problem deepened my appreciation for how data structure cloning works — not just duplicating values, but preserving relationships! #LeetCode #100DaysOfCode #Day52 #Java #LinkedList #DeepCopy #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
🚀 Day 29 of #100DaysOfCode – LeetCode Problem #643: Maximum Average Subarray I 🧩 Problem: Given an integer array nums and an integer k, find the contiguous subarray of length k that has the maximum average value. 💡 Approach: This problem is a great example of the Sliding Window Technique 🪟 Calculate the sum of the first k elements. Then slide the window by one element at a time — subtract the element that goes out, add the new one coming in. Keep track of the maximum sum seen. Return the maximum average (maxSum / k). 💻 Java Code: class Solution { public double findMaxAverage(int[] nums, int k) { double sum = 0; for (int i = 0; i < k; i++) { sum += nums[i]; } double max = sum; for (int i = k; i < nums.length; i++) { sum += nums[i] - nums[i - k]; max = Math.max(max, sum); } return max / k; } } ⏱️ Complexity: Time: O(n) Space: O(1) ✅ Result: Accepted (Runtime: 0 ms) This one reinforces how sliding window optimizations can drastically simplify what looks like a brute-force problem!
To view or add a comment, sign in
-
🚀 Day 47 of #100DaysOfCode – LeetCode Problem #1013: Partition Array Into Three Parts With Equal Sum 💬 Problem Summary: Given an array of integers, determine whether it can be split into three non-empty parts such that: Each part has the same sum, and The partitions appear in order (left → mid → right). Formally, we need to find indices i + 1 < j such that: sum(arr[0..i]) == sum(arr[i+1..j-1]) == sum(arr[j..end]) 🧩 Examples: Input: [0,2,1,-6,6,-7,9,1,2,0,1] Output: true ✔️ Three parts sum to 3 each. Input: [0,2,1,-6,6,7,9,-1,2,0,1] Output: false 🧠 Logic: This challenge focuses on finding equal prefix sums: 1️⃣ Compute total sum of the array. 2️⃣ If total sum is not divisible by 3 → ❌ impossible. 3️⃣ Walk through the array, accumulating values. 4️⃣ Each time a segment equals target = totalSum / 3, increase the partition count. 5️⃣ If we find 2 such partitions before the last index → array can be divided. 💻 Java Solution: class Solution { public boolean canThreePartsEqualSum(int[] arr) { int total = 0; for(int num : arr) total += num; if(total % 3 != 0) return false; int target = total / 3; int sum = 0, count = 0; for(int i = 0; i < arr.length; i++) { sum += arr[i]; if(sum == target) { count++; sum = 0; if(count == 2 && i < arr.length - 1) return true; } } return false; } } ⚙️ Complexity: Time: O(n) Space: O(1) ✅ Result: Accepted (Runtime: 0 ms) 💬 Takeaway: A great pattern-recognition problem—once you realize that only two valid partitions are needed (the third is implied), the solution becomes clean and efficient.
To view or add a comment, sign in
-
𝗕𝗲𝗵𝗶𝗻𝗱 𝘁𝗵𝗲 𝗦𝗰𝗲𝗻𝗲𝘀 𝗼𝗳 𝗝𝗮𝘃𝗮 𝗔𝗿𝗿𝗮𝘆𝗟𝗶𝘀𝘁! Today, I implemented a 𝗗𝘆𝗻𝗮𝗺𝗶𝗰 𝗔𝗿𝗿𝗮𝘆 in Java — building the logic from scratch to understand how ArrayList actually works under the hood. ⚙️ This exercise gave me hands-on exposure to how resizing, shifting, and accessing elements are efficiently handled in dynamic data structures. 𝗛𝗲𝗿𝗲’𝘀 𝘄𝗵𝗮𝘁 𝗜 𝗶𝗺𝗽𝗹𝗲𝗺𝗲𝗻𝘁𝗲𝗱 👇 🔹 add(element) — to append new items dynamically 🔹 add(index, element) — to insert at a specific position 🔹 get(index) — to fetch values efficiently 🔹 set(index, element) — to replace existing elements 🔹 remove(index/element) — to delete items and shift elements 🔹 contains(element) — to check for existence 🔹 isEmpty() & clear() — to manage and reset the structure 𝗜𝗺𝗽𝗹𝗲𝗺𝗲𝗻𝘁𝗮𝘁𝗶𝗼𝗻 𝗖𝗼𝗱𝗲 : https://lnkd.in/gXEfwXvf 📘 𝗞𝗲𝘆 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆: Recreating ArrayList from scratch deepened my understanding of how memory reallocation, indexing, and dynamic resizing make it one of the most powerful data structures in Java’s Collection Framework. Learning the “how” behind the “what” truly builds stronger foundations. 💪 #Java #DataStructures #ArrayList #CodingJourney #LearningByDoing #SoftwareEngineering #DSA #100DaysOfCode
To view or add a comment, sign in
-
-
✅ Day 35 of #100DaysOfCode Challenge 📘 LeetCode Problem 112: Path Sum 🧩 Problem Statement: Given the root of a binary tree and an integer targetSum, return true if there exists a root-to-leaf path whose sum of node values equals targetSum. Example: Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22 Output: true Explanation: Path 5 → 4 → 11 → 2 gives the sum = 22 ✅ 💡 Simple Approach: If the tree is empty → return false If it’s a leaf node → check if its value equals targetSum Otherwise → subtract node value and check left and right recursively 💻 Easiest Java Code: class Solution { public boolean hasPathSum(TreeNode root, int sum) { if (root == null) return false; if (root.left == null && root.right == null && root.val == sum) return true; sum = sum - root.val; return hasPathSum(root.left, sum) || hasPathSum(root.right, sum); } } ⚙️ Complexity: ⏱️ Time: O(n) → visit each node once 💾 Space: O(h) → recursion stack (h = height of tree) 🌿 Small code, big concept — recursion makes trees easy 🌱 #Day35 #100DaysOfCode #LeetCode #Java #DSA #BinaryTree #Recursion #CodingChallenge
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