Day 4/100 – LeetCode Challenge Problem Solved: Find First and Last Position of Element in Sorted Array (34) Today I worked on a problem that requires finding the starting and ending index of a target value in a sorted array. If the target is not present, the result should be [-1, -1]. The important constraint is that the solution must run in O(log n) time. Since the array is sorted, this naturally points to Binary Search. Instead of performing a simple search, the idea is to perform two modified binary searches: One to find the first occurrence of the target, and another to find the last occurrence. By carefully adjusting the search boundaries when the target is found, we can narrow down the exact range. This ensures: The algorithm maintains logarithmic time complexity. The solution handles duplicates correctly. Edge cases such as the target not being present are properly addressed. Time Complexity: O(log n) Space Complexity: O(1) Key takeaway: Binary search is not just about finding whether an element exists. With small boundary modifications, it can be adapted to solve range-based problems efficiently. Understanding how to tweak the search condition is more important than memorizing the template. Day 4 completed. Continuing to sharpen problem-solving fundamentals. #100DaysOfLeetCode #BinarySearch #Java #DataStructures #ProblemSolving #Consistency
Binary Search for First and Last Position in Sorted Array
More Relevant Posts
-
Day 16/100 – LeetCode Challenge Problem Solved: Binary Tree Level Order Traversal Today’s problem focused on traversing a binary tree level by level. Instead of visiting nodes in depth-first order, the goal is to group nodes according to their depth in the tree. The idea behind the solution is to track the level of each node while traversing the tree. Starting from the root at level 0, each recursive call increases the level for its child nodes. When visiting a node, we check whether a list for that level already exists. If not, we create one; otherwise, we append the node value to the existing level list. By doing this, the traversal naturally organizes nodes into separate lists representing each level of the tree. Time Complexity: O(n) Space Complexity: O(n) Key takeaway: Tree problems often become easier when you track additional context during traversal. In this case, maintaining the current level allows the recursion to build a structured level-by-level result. Day 16 completed. Continuing the consistency streak and strengthening tree traversal concepts. #100DaysOfLeetCode #Java #BinaryTree #TreeTraversal #Algorithms #ProblemSolving
To view or add a comment, sign in
-
-
🔥 Day 97 of #100DaysOfCode Today’s problem: LeetCode – Search in Rotated Sorted Array 🔄🔍 📌 Problem Summary You are given a rotated sorted array and a target. Your task is to return the index of the target if it exists; otherwise return -1. Example: Input: nums = [4,5,6,7,0,1,2], target = 0 Output: 4 🧠 Approach Used: Linear Search In this solution, we simply iterate through the array and check if the current element equals the target. ⚙️ Logic for(int i = 0; i < nums.length; i++){ if(nums[i] == target){ return i; } } return -1; 💡 Explanation Traverse the array from start to end If the target is found → return the index If the loop finishes → return -1 ⏱ Time Complexity: O(n) 💾 Space Complexity: O(1) 🚀 Performance Runtime: 0 ms Memory: 43.68 MB 🧠 Learning This problem can also be solved using Binary Search in O(log n) by identifying which half of the rotated array is sorted. But for smaller inputs or quick validation, linear scan works correctly and is simple to implement. Only 3 days left to complete the #100DaysOfCode challenge 🚀 Consistency is the real win here! On to Day 98 🔥 #100DaysOfCode #LeetCode #Java #DSA #CodingJourney #InterviewPrep
To view or add a comment, sign in
-
-
🚀 Day 17/100 – Sorted Squares (Two Pointer Approach) Today I solved the “Sorted Squares” problem on LeetCode. 🔹 Problem: Given a sorted array (non-decreasing order), return an array of the squares of each number, also sorted. 🔹 Brute Force Idea: 1. Square each element. 2. Sort the array again. Time Complexity: O(n log n) ❌ (Not optimal because sorting takes extra time.) 🔹 Optimal Approach (Two Pointer Technique): Since the array is already sorted, the largest square will come from either: - The leftmost negative number - Or the rightmost positive number So I used: • left pointer at start • right pointer at end • filled the result array from the back At each step: Compare absolute values Place the larger square at the current index Move the corresponding pointer ⏱ Time Complexity: O(n) 📦 Space Complexity: O(n) ✨ Key Learning: Instead of blindly sorting again, understanding the pattern of negative numbers helped me optimize the solution. #Day17 #100DaysOfCode #LeetCode #Java #DataStructures #Arrays.
To view or add a comment, sign in
-
-
Merge Sorted Array (LeetCode : 88) 💻✨ In this problem, we are given two sorted arrays. The task is to create a final sorted array inside nums1 without using extra space. I used Two Pointer Technique here 👇 🔹 i → last valid index of nums1 🔹 j → last index of nums2 🔹 k → last index of nums1 (m + n - 1) We compare from the back because if we compare from the front, the data would be overwritten. 👉 If nums1[i] > nums2[j], then we put the larger value at the back. 👉 Otherwise, we put nums2[j]. 👉 Once any one of the arrays is finished, we copy the remaining elements. Time Complexity of this approach: O(m + n) Space Complexity: O(1) (In-place solution) 🚀 This problem reminded me again — If you think in the right direction, the solution becomes much easier. #LeetCode #androidDeveloper#problemslover#dsapattern#twopointer#dailyChallenge #DSA #Java #TwoPointerTechnique #ProblemSolving #CodingJourney #SoftwareDevelopment #InPlaceAlgorithm #DataStructures #AlgorithmThinking
To view or add a comment, sign in
-
-
Day 16/100 – LeetCode Challenge Problem: Merge Sorted Array Today’s problem involved merging two sorted arrays into one sorted array. Approach: Created a temporary array of size m + n Used two pointers to compare elements from both arrays Inserted the smaller element into the new array Copied remaining elements if any array still had values Finally copied the merged result back into nums1 Complexity: Time: O(m + n) Space: O(m + n) Concepts Practiced: Two-pointer technique Array traversal Merging sorted arrays #100DaysOfCode #LeetCode #DSA #Java #Arrays #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
Day 18/100 – LeetCode Challenge Problem Solved: Reverse Linked List Today’s problem focused on reversing a singly linked list. While it looks simple, it’s a fundamental concept that tests pointer manipulation and understanding of linked structures. The idea is to iterate through the list and reverse the direction of each node’s pointer. At every step, we keep track of three things: the current node, the previous node, and the next node. We reverse the link by pointing the current node to the previous one, then move all pointers one step forward. By the end of the traversal, the previous pointer will be pointing to the new head of the reversed list. Time Complexity: O(n) Space Complexity: O(1) Performance: Runtime 0 ms Key takeaway: Linked list problems are all about pointer control. Mastering how pointers move and change direction is essential for solving more complex problems efficiently. Day 18 completed. Staying consistent and reinforcing core data structure fundamentals. #100DaysOfLeetCode #Java #LinkedList #Algorithms #ProblemSolving #Consistency
To view or add a comment, sign in
-
-
🚀 Day 34 of #100DaysOfCode Solved 852. Peak Index in a Mountain Array on LeetCode ⛰️📈 🧠 Key Insight: A mountain array strictly increases to a peak and then decreases. Instead of scanning the whole array, we can use Binary Search to efficiently find the peak. ⚙️ Approach: 🔹Use binary search with two pointers left and right 🔹Compare arr[mid] with arr[mid + 1] 🔹If arr[mid] > arr[mid + 1] → peak is on the left side (including mid) 🔹Otherwise → peak is on the right side 🔹Continue until left == right, which gives the peak index ⏱️ Time Complexity: O(log n) 📦 Space Complexity: O(1) #100DaysOfCode #LeetCode #DSA #BinarySearch #Arrays #Java #ProblemSolving #InterviewPrep #LearningInPublic
To view or add a comment, sign in
-
-
🔥 Day 98 of #100DaysOfCode Today’s challenge: LeetCode – Search in Rotated Sorted Array II 🔄🔍 📌 Problem Summary You are given a rotated sorted array that may contain duplicates. Your task is to determine whether a target exists in the array. Example: Input: nums = [2,5,6,0,0,1,2], target = 0 Output: true 🧠 Approach Used: Linear Search In this implementation, we simply iterate through the array and check if the element matches the target. ⚙️ Logic for(int i = 0; i < nums.length; i++){ if(nums[i] == target){ return true; } } return false; 💡 Explanation Traverse the array from start to end If the target is found → return true If the loop finishes → return false ⏱ Time Complexity: O(n) 💾 Space Complexity: O(1) 🚀 Performance Runtime: 0 ms Memory: 44.9 MB 🧠 Learning This problem is a variation of Search in Rotated Sorted Array, but with duplicates allowed. While a Binary Search solution exists, duplicates can break the strict ordering and make the logic more complex. A simple linear scan ensures correctness in all cases. Only 2 days left to complete #100DaysOfCode 🚀 Almost at the finish line! On to Day 99 🔥 #100DaysOfCode #LeetCode #Java #DSA #CodingJourney #InterviewPrep
To view or add a comment, sign in
-
-
✳️Day 20 of #100DaysOfCode✳️ 🚀 New Problem Solved: Largest Subarray with 0 Sum! 🛠️ The Logic Behind the Code: To solve this efficiently, I used a HashMap to track prefix sums and their first occurrences. Here are the key steps I followed: Prefix Sum Tracking: As I iterate through the array, I maintain a running sum of the elements. The Base Case: If the sum itself becomes 0 at any point, the subarray from the very beginning to the current index i has a sum of 0. I update the max length to i + 1. Hashing for Efficiency: If the current sum has been seen before in the HashMap, it means the elements between the previous occurrence and the current index must add up to 0. I calculate the distance (current\_index - previous\_index) and update my maxLen. Storing New Sums: If the sum is new, I store it in the map with its index to ensure I always calculate the largest possible distance later. Complexity: Time: O(n) — We only traverse the array once. Space: O(n) — To store the prefix sums in the Map. #DataStructures #Algorithms #Java #CodingLife #GeeksforGeeks #ProblemSolving #SoftwareEngineering
To view or add a comment, sign in
-
-
Day 65/100 – LeetCode Challenge ✅ Problem: #22 Generate Parentheses Difficulty: Medium Language: Java Approach: Backtracking with State Tracking Time Complexity: O(4ⁿ/√n) — Catalan number Space Complexity: O(n) for recursion stack Key Insight: Valid parentheses require at every prefix: Open brackets can be added anytime (open < n) Close brackets only when close < open (never close more than opened) When string length reaches 2n, add to result. Solution Brief: Recursive backtracking maintaining counts of open and close brackets used. Two branching conditions: Add '(' if open < n Add ')' if close < open Base case: when length = 2n, add valid combination to list. #LeetCode #Day65 #100DaysOfCode #Backtracking #Java #Algorithm #CodingChallenge #ProblemSolving #GenerateParentheses #MediumProblem #Recursion #StringManipulation #DSA
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