Day 25 of Daily DSA 🚀 Solved LeetCode 155: Min Stack ✅ Problem: Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. Approach: Used two stacks: main stack → stores all elements min stack → keeps track of the current minimum Key idea: When pushing a value, also push it to min stack if it is ≤ current minimum During pop, if the popped value equals the top of min stack, pop from min as well This ensures the minimum element is always available in O(1) time. ⏱ Complexity: • push() → O(1) • pop() → O(1) • top() → O(1) • getMin() → O(1) 📊 LeetCode Stats: • Runtime: 5 ms (Beats 83.96%) ⚡ • Memory: 47.15 MB Great problem to understand stack design patterns and auxiliary data structures. #DSA #LeetCode #Java #DataStructures #CodingJourney #ProblemSolving
Design Min Stack with Constant Time Complexity
More Relevant Posts
-
Day 31 of Daily DSA 🚀 Solved LeetCode 724: Find Pivot Index ✅ Problem: Given an array of integers, find the pivot index — where the sum of all numbers strictly to the left equals the sum of all numbers strictly to the right. Rules: * If the index is on the left edge → left sum is 0 * If the index is on the right edge → right sum is 0 * Return the leftmost pivot index, or -1 if none exists Approach: Used Prefix Sum logic to efficiently track left and right sums in a single pass. Steps: 1. Calculate the total sum of the array (rSum) 2. Iterate through the array, reducing rSum by current element 3. If rSum equals lSum → pivot index found! 4. Add current element to lSum and continue ⏱ Complexity: • Time: O(n) • Space: O(1) 📊 LeetCode Stats: • Runtime: 1 ms (Beats 98.65%) ⚡ • Memory: 47.65 MB A clean example of how prefix sums eliminate the need for nested loops and make array problems lightning fast. #DSA #LeetCode #Java #PrefixSum #Arrays #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
📌 Median of Two Sorted Arrays Platform: LeetCode #4 Difficulty: Hard ⚙️ Approach • Apply binary search on the smaller array for efficiency • Define search space from 0 to n1 • Partition both arrays such that: – Left half contains (n1 + n2 + 1) / 2 elements – Right half contains remaining elements • Identify boundary elements: – l1, l2 → left side elements – r1, r2 → right side elements • Check valid partition: – l1 <= r2 and l2 <= r1 • If valid: – For even length → median = average of max(left) and min(right) – For odd length → median = max(left) • If not valid: – If l1 > r2, move left – Else move right 🧠 Logic Used • Binary Search on partition index • Dividing arrays into balanced halves • Handling edge cases using boundary values • Achieving optimal O(log(min(n1, n2))) time complexity 🔗 GitHub: https://lnkd.in/g_3x55n8 ✅ Day 36 Completed – Revised advanced binary search and partition-based problem. #100DaysOfCode #Java #DSA #ProblemSolving #CodingJourney #Algorithms #DataStructures #LeetCode #CodingPractice #CodeEveryDay #BinarySearch #ArrayProblems
To view or add a comment, sign in
-
-
📘 DSA Journey — Day 22 Today’s focus: Prefix Sum + Fixed Window optimization. Problem solved: • K Radius Subarray Averages (LeetCode 2090) Concepts used: • Prefix Sum • Fixed-size sliding window • Efficient range sum calculation Key takeaway: The goal is to calculate the average of subarrays centered at each index with radius k. A brute-force approach would recompute sums for every index, leading to O(n·k) time. Instead, using prefix sum, we can compute any subarray sum in O(1) time. For each index i, the valid window is: [i - k, i + k] If this window is within bounds, we calculate the sum using prefix sum and divide by (2k + 1). If not enough elements exist on either side, we return -1. This approach reduces the complexity to O(n) and avoids repeated calculations. This problem highlights how prefix sum helps in efficiently handling range-based queries. Continuing to strengthen fundamentals and consistency in DSA problem solving. #DSA #Java #LeetCode #CodingJourney
To view or add a comment, sign in
-
-
Day 45 of Daily DSA 🚀 Solved LeetCode 867: Transpose Matrix ✅ Problem: Given a 2D matrix, return its transpose (rows become columns and columns become rows). Approach: Created a new matrix and swapped indices while traversing. Steps: Get number of rows and columns Create a new matrix of size cols x rows Traverse original matrix Assign: trans[j][i] = matrix[i][j] Return the new matrix ⏱ Complexity: • Time: O(n × m) • Space: O(n × m) 📊 LeetCode Stats: • Runtime: 0 ms (Beats 100%) ⚡ • Memory: 46.46 MB Simple transformations like transpose build strong fundamentals for matrix-based problems 💡 #DSA #LeetCode #Java #Arrays #Matrix #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
🔥 Day 364 – Daily DSA Challenge! 🔥 Problem: 🎯 Find K Closest Elements Given a sorted array arr, an integer k, and a target x, return the k closest elements to x in ascending order. 💡 Key Insight — Binary Search on Window Instead of checking each element, we binary search the starting index of a window of size k. Search space: Possible windows → [0 ... n - k] 🧠 Decision Logic At index mid, compare: Distance of left boundary → x - arr[mid] Distance of right boundary → arr[mid + k] - x We choose direction based on: ⚡ Algorithm Steps ✅ Initialize: left = 0, right = n - k ✅ Binary search: If left side is farther → shift right Else → move left ✅ Final window starts at left ✅ Collect k elements ⚙️ Complexity ✅ Time Complexity: O(log(n - k) + k) (binary search + result building) ✅ Space Complexity: O(k) 💬 Challenge for you 1️⃣ Why do we search on window positions instead of elements? 2️⃣ Can you solve this using a heap approach? 3️⃣ What if array was unsorted? #DSA #Day364 #LeetCode #BinarySearch #SlidingWindow #Arrays #Java #ProblemSolving #KeepCoding
To view or add a comment, sign in
-
-
Day #8 / 100 – Data Structures & Algorithms Today’s focus was on advanced linked list problems and pointer manipulation. Problems solved: • Flatten a Multilevel Doubly Linked List • Design Browser History • Insertion in Circular Linked List • Swap Kth Nodes from End • Rotate the List • Insert Node in a Doubly Linked List • Delete Node in Doubly Linked List • Copy List with Random Pointer Key takeaway: Linked list problems heavily test pointer management and edge case handling, especially when working with structures like circular lists, multilevel lists, or random pointers. Consistent practice is helping strengthen problem-solving and implementation skills while preparing for backend engineering roles. #100DaysOfCode #DSA #LeetCode #Java #BackendDevelopment #Acciojob
To view or add a comment, sign in
-
-
🔥 Day 82 of my LeetCode Journey 🔥 📘 Problem: 110. Balanced Binary Tree 🎯 Difficulty: Easy 🔹 Problem Statement: Given a binary tree, determine if it is height-balanced. A binary tree is balanced if the height difference between the left and right subtree of every node is not more than 1. 🔹 Approach Used: Traverse the tree using Depth First Search (DFS) Calculate the height of left and right subtrees recursively If the height difference exceeds 1, return -1 to indicate the tree is not balanced Otherwise, return the height of the current node Finally, check if the returned value is -1 or not 🔹 Key Concepts: Binary Tree traversal Depth First Search (DFS) Recursion Height calculation of tree 🔹 Learning: Instead of calculating heights separately for every node (which would increase complexity), this approach combines height calculation and balance checking in a single traversal, making the solution more efficient. Time Complexity: O(n) Space Complexity: O(h) (recursion stack) #LeetCode #Day82 #Java #BinaryTree #DFS #Recursion #DSA #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
Day 41/100 🚀 | #100DaysOfDSA Solved Valid Perfect Square (LeetCode 367) today. The task was to determine whether a number is a perfect square without using built-in functions like sqrt(). Approach: Used Binary Search to efficiently find a number whose square equals the given number. Steps: • Initialize left = 1 and right = num • Calculate mid • If mid * mid == num, it's a perfect square • If mid * mid < num, move to the right half • Otherwise, search the left half Also used long to prevent overflow while calculating mid * mid. Time Complexity: O(log n) Space Complexity: O(1) Key takeaway: Binary Search isn’t just for arrays — it can also be applied to mathematical search spaces. #LeetCode #DSA #BinarySearch #Java #ProblemSolving #100DaysOfDSA
To view or add a comment, sign in
-
-
🚀 Day 42 of #100DaysOfCode Solved 1508. Range Sum of Sorted Subarray Sums on LeetCode 📊 🧠 Problem Insight: Given an array, we must compute the sum of all subarray sums, sort them, and return the sum of elements between indices left and right. ⚙️ Approach Used: 1️⃣ Generate all possible subarray sums using nested loops 2️⃣ Store them in an array of size n*(n+1)/2 3️⃣ Sort the subarray sums 4️⃣ Compute the sum of elements from index left-1 to right-1 5️⃣ Apply mod = 1e9 + 7 to avoid overflow This approach works well because the total number of subarrays is manageable for the given constraints. ⏱️ Time Complexity: O(n² log n) O(n²) to generate subarray sums O(n² log n) to sort them 📦 Space Complexity: O(n²) #100DaysOfCode #LeetCode #DSA #Arrays #Algorithms #Java #CodingPractice #InterviewPrep
To view or add a comment, sign in
-
-
📘 DSA Journey — Day 28 Today’s focus: Binary Search for minimum in rotated arrays. Problem solved: • Find Minimum in Rotated Sorted Array (LeetCode 153) Concepts used: • Binary Search • Identifying unsorted half • Search space reduction Key takeaway: The goal is to find the minimum element in a rotated sorted array. Using binary search, we compare the mid element with the rightmost element: • If nums[mid] > nums[right] → minimum lies in the right half • Else → minimum lies in the left half (including mid) This works because the rotation creates one unsorted region, and the minimum always lies in that region. By narrowing the search space each time, we achieve O(log n) time complexity. This problem highlights how slight modifications in array structure still allow binary search to work efficiently with the right observations. Continuing to strengthen binary search patterns and consistency in problem solving. #DSA #Java #LeetCode #CodingJourney
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