Day - 75 Next Greater Element I The problem - Given two arrays nums1 and nums2 where nums1 is a subset of nums2, for each element in nums1, find the next greater element in nums2. The next greater element is the first greater element to the right. If it doesn't exist, return -1. Brute Force - For each element in nums1, find its position in nums2, then scan right to find the first greater element. This gives O(n × m) time complexity where n = length of nums1 and m = length of nums2. Approach Used - •) Create array nextGreater[10001] to store next greater element for each number and a Stack<Integer> for tracking elements. •) Traverse nums2 from right to left (i = length-1 to 0), 1 - While stack is not empty && stack.peek() ≤ nums2[i], pop from stack. 2 - If stack is empty, nextGreater[nums2[i]] = -1, else nextGreater[nums2[i]] = stack.peek(). 3 - Push nums2[i] onto stack. •) For each element in nums1, replace it with nextGreater[nums1[i]], return nums1. Complexity - Time - O(n + m) where n = nums1.length, m = nums2.length. Space - O(m), for stack and nextGreater array. Note - Using a monotonic decreasing stack while traversing right to left allows us to efficiently find the next greater element. Elements smaller than current are popped (they can't be next greater for anyone), and the remaining top element is the answer. The array acts as a lookup table for O(1) retrieval. #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving
Next Greater Element in Subset Array
More Relevant Posts
-
Day - 78 Next Greater Element II The problem - Given a circular integer array nums (the next element of nums[nums.length - 1] is nums[0]), return the next greater number for every element in nums. The next greater number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, return -1 for this number. Brute Force - For each element, traverse the array circularly (wrap around using modulo) to find the first greater element. This gives O(n²) time complexity, as for each element we potentially scan the entire array. Approach Used - •) Initialize, create Stack<Integer> to maintain elements in decreasing order, create ans[] array of size n to store results, set n = nums.length. •) For each index i = 2 × n - 1 down to i = 0, 1 - Get current element: current = nums[i % n]. 2 - While stack is not empty AND st.peek() <= current, pop from stack. 3 - If i < n: ans[i] = st.isEmpty()arr ? -1 : st.peek(). 4 - Push current onto stack. •) Return ans[] array. Complexity - Time - O(n), each element pushed and popped from stack at most once across both passes. Space - O(n), for stack and result array. Note - By traversing the array twice (2n iterations) in reverse order, we simulate the circular nature of the array. The stack maintains elements in decreasing order, and for each element, the top of the stack is the next greater element. The modulo operation i % n handles the circular indexing, and we only store results during the second half of the traversal (when i < n). #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving
To view or add a comment, sign in
-
-
Solved: Binary Tree Maximum Path Sum (LeetCode – Hard) I recently solved the Maximum Path Sum problem in a binary tree, a classic interview question that strengthens recursion and tree traversal concepts. ->Used postorder traversal (process left → right → node). ->Ignored negative subtree sums to avoid reducing the total. ->Maintained a global variable to track the maximum path found so far. ->Returned only the best single-branch path to the parent node. Key Takeaways: 1. Clear understanding of recursion flow is essential. 2. Careful handling of negative values improves correctness. Time Complexity: O(N) Space Complexity: O(H) #LeetCode #Java #BinaryTree #DataStructures #CodingInterview
To view or add a comment, sign in
-
-
🚀 DSA Daily Challenge – Day 7 🧠 Problem: Remove Element (LeetCode 27) 💡 Problem Statement: Given an integer array nums and an integer val, remove all occurrences of val in-place and return the number of remaining elements. ⚠️ You must modify the array in-place with O(1) extra space. 🔥 Intuition Brute force idea: Create a new array and copy elements ≠ val ❌ But the problem requires in-place modification. So how do we solve it efficiently? 👉 Use the Two Pointer Technique 🛠 Approach (Two Pointers – In Place) • Use one pointer i to traverse the array • Use another pointer index to track where the next valid element should go • If nums[i] != val → copy it to nums[index] • Increment index At the end, index represents the new length. ⚙️ Complexity ⏱ Time Complexity: O(n) 📦 Space Complexity: O(1) 👉 Think Two Pointers + Overwriting Pattern This pattern is very common in coding interviews 🔥 #LeetCode #LeetCode27 #RemoveElement #DSA #DataStructures #Algorithms #CodingInterview #InterviewPreparation #Java #TwoPointers #ArrayProblems #InPlaceAlgorithm #TimeComplexity #BigO #CompetitiveProgramming #FAANGPrep #100DaysOfCode
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 82 of #100DaysOfCode Today’s problem: LeetCode: Permutation in String 🧠 📌 Problem Summary Given two strings s1 and s2, return true if s2 contains a permutation of s1. Example: s1 = "ab" s2 = "eidbaooo" Output → true (because "ba" exists in s2) 🧠 Approach: Sliding Window + Frequency Count (Optimized) Key Idea: If a permutation exists, then some substring of s2 must: Have the same length as s1 Have the same character frequency ⚙️ Steps: If s1.length() > s2.length() → return false Maintain: int[26] s1Count int[26] s2Count Fill both arrays for first window Slide window across s2 Compare frequency arrays To optimize comparison: Track a matches counter When all 26 characters match → permutation found ⏱ Time Complexity: O(n) 💾 Space Complexity: O(1) (fixed 26 letters) 💡 What I Learned Sliding window problems become easier when you convert strings into frequency arrays. Tracking “matches” instead of comparing arrays every time improves performance. This is a classic interview problem for FAANG-level companies. Consistency is compounding. Sliding window mastery getting sharper every day. 🔥 On to Day 83 🚀 #100DaysOfCode #LeetCode #SlidingWindow #Java #DSA #CodingJourney #InterviewPrep
To view or add a comment, sign in
-
-
Day - 90 Binary Tree Maximum Path Sum The problem - Given the root of a binary tree, return the maximum path sum of any non-empty path. A path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root. The path sum is the sum of the node values in the path. Brute Force - For each node, consider all possible paths starting from that node using DFS, calculate their sums, and track the maximum. This gives O(n²) time complexity as we explore multiple paths from each node with redundant calculations. Approach Used - •) Declare res = {root.val}. •) Call helper function: dfs(root , res). •) Return res[0]. Helper Function - dfs( Treenode node , int[] res) •) If node == null, return 0 (no contribution from null node). •) leftSum = Math.max(0, dfs(node.left, res)), taking max with 0 to ignore negative paths. •) rightSum = Math.max(0, dfs(node.right, res)), taking max with 0 to ignore negative paths. •) Update maximum sum, res[0] = Math.max(res[0], leftSum + rightSum + node.val), this considers path through current node connecting both subtrees. •) Return Math.max(leftSum, rightSum) + node.val, parent can use only one branch left or right. Complexity - Time - O(n), where n = number of nodes. Space - O(h), where h = height of tree. Note - At each node, we consider two scenarios: (1) the maximum path passing through this node (connecting both subtrees), which updates the global maximum, and (2) the maximum path extending from this node to its parent (using only one subtree), which is returned. We use Math.max(0, childSum) to ignore negative contributions, as excluding negative paths yields better sums. #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving
To view or add a comment, sign in
-
-
🔥 Day 83 of #100DaysOfCode Today’s problem: LeetCode: Minimum Size Subarray Sum 🎯 📌 Problem Summary Given: An integer target An array nums Return the minimum length of a contiguous subarray whose sum is greater than or equal to target. If no such subarray exists → return 0. Example: target = 7 nums = [2,3,1,2,4,3] Output → 2 (because [4,3] = 7) 🧠 Approach: Sliding Window (Two Pointers) This is a classic variable-size sliding window problem. ⚙️ Strategy: Use two pointers: l (left) and r (right) Expand window by moving r Keep adding to total When total >= target: Update result Shrink window from left Subtract from total 🔁 Core Logic: for each r: total += nums[r] while total >= target: update min length total -= nums[l] l++ ⏱ Time Complexity: O(n) 💾 Space Complexity: O(1) 💡 What I Learned Sliding window is extremely powerful for subarray problems. The key is knowing when to expand and when to shrink. Many medium/hard problems are just variations of this pattern. Today’s runtime: ⚡ 1ms (99% faster) Consistency builds mastery. On to Day 84 🚀 #100DaysOfCode #LeetCode #SlidingWindow #Java #DSA #InterviewPrep #CodingJourney
To view or add a comment, sign in
-
-
Day 17/30 – LeetCode streak Today’s problem: Find Kth Bit in Nth Binary String (1545). 'S₁ = "0"', and 'Sₙ = Sₙ₋₁ + "1" + reverse(invert(Sₙ₋₁))'. Length of 'Sₙ' is always '2ⁿ - 1', with a '1' sitting exactly in the middle. The structure looks like this: Sₙ = [Sₙ₋₁] + '1' + reverse(invert(Sₙ₋₁)) So for any position 'k': - Let 'mid = 2^(n-1)' (the middle index, 1-based). - If 'k == mid', answer is '1'. - If 'k < mid', it’s in the left half, which is exactly 'Sₙ₋₁' → recurse: 'findKthBit(n-1, k)'. - If 'k > mid', it’s in 'reverse(invert(Sₙ₋₁))'. Mirror it back into 'Sₙ₋₁' at 'mirror = 2*mid - k' (same as '2ⁿ - k'), recursively get that bit from 'Sₙ₋₁', then flip it. Day 17 takeaway: This is one of those problems where drawing the recursive construction once (left + 1 + reversed/inverted left) makes the “mid / mirror / invert” recursion feel natural—and you never have to actually build the string. #leetcode #dsa #java #recursion #consistency
To view or add a comment, sign in
-
-
🚀 Day 38 of #100DaysOfCode Solved 154. Find Minimum in Rotated Sorted Array II on LeetCode 🔍 🧠 Key Insight: The array is sorted but rotated, and this version introduces duplicates, which makes the binary search logic slightly trickier. ⚙️ Approach: 🔹Use binary search with left and right pointers 🔹Compare nums[mid] with nums[right]: 🔹If nums[mid] > nums[right] → minimum lies in the right half 🔹If nums[mid] < nums[right] → minimum lies in the left half (including mid) 🔹If equal → safely shrink the search space by decrementing right This handles the ambiguity caused by duplicates. ⏱️ Time Complexity: Average: O(log n) Worst case: O(n) (when many duplicates exist) 📦 Space Complexity: O(1) #100DaysOfCode #LeetCode #DSA #BinarySearch #Arrays #Java #ProblemSolving #InterviewPrep #LearningInPublic
To view or add a comment, sign in
-
-
Day 14/100 | #100DaysOfDSA Today’s problem: Search a 2D Matrix At first glance, it looks like a 2D search problem… But the trick? Treat the matrix like a sorted 1D array. Since: • Each row is sorted • First element of every row > last element of previous row That means the entire matrix is globally sorted. Approach: • Apply Binary Search • Convert mid index → row = mid / n, col = mid % n • Compare and adjust pointers Time complexity: O(log(m × n)) Big takeaway: Sometimes the problem isn’t 2D at all — it’s just perspective. Stacking binary search patterns now. 🚀 #100DaysOfCode #LeetCode #DSA #Algorithms #BinarySearch #Java #CodingJourney #ProblemSolving #InterviewPrep #TechCommunity #SoftwareEngineer #ComputerScience #Consistency #Programmers #TechGrowth
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