💻✨ 𝗟𝗲𝗲𝘁𝗖𝗼𝗱𝗲 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 𝟰𝟵𝟲 | 𝗡𝗲𝘅𝘁 𝗚𝗿𝗲𝗮𝘁𝗲𝗿 𝗘𝗹𝗲𝗺𝗲𝗻𝘁 𝗜 ✨💻 Today I worked on an interesting challenge — “Next Greater Element I”, a problem that tests both logical reasoning and data structure efficiency 🔍 🔹 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 𝗦𝘁𝗮𝘁𝗲𝗺𝗲𝗻𝘁 (𝗦𝗶𝗺𝗽𝗹𝗶𝗳𝗶𝗲𝗱): Given two arrays nums1 and nums2, for each element in nums1, find the first greater element to its right in nums2. If no such element exists ➜ return -1. 🔹 𝗞𝗲𝘆 𝗖𝗼𝗻𝗰𝗲𝗽𝘁𝘀 𝗨𝘀𝗲𝗱: ✅ Stack (for tracking next greater efficiently) ✅ HashMap (for constant-time lookup) ✅ Reverse traversal → O(n) time 🔹 𝗠𝘆 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵: Instead of using a brute-force O(n²) method, I used a monotonic decreasing stack, a powerful pattern for such problems — improving efficiency from O(n²) ➜ O(n) 🚀 Here’s a glimpse of my Java solution 👇 Stack<Integer> st = new Stack<>(); for (int i = n - 1; i >= 0; i--) { while (!st.isEmpty() && nums2[i] >= st.peek()) st.pop(); nge[i] = st.isEmpty() ? -1 : st.peek(); st.push(nums2[i]); } 🧠 𝗟𝗲𝗮𝗿𝗻𝗶𝗻𝗴 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆: Choosing the right data structure can turn a complex problem into an elegant one. Always enjoy challenges that combine algorithmic thinking + clean code design 💡 #𝗝𝗮𝘃𝗮 #𝗖𝗼𝗱𝗶𝗻𝗴 #𝗗𝗦𝗔 #𝗟𝗲𝗲𝘁𝗖𝗼𝗱𝗲 #𝗣𝗿𝗼𝗯𝗹𝗲𝗺𝗦𝗼𝗹𝘃𝗶𝗻𝗴 #𝗦𝗼𝗳𝘁𝘄𝗮𝗿𝗲𝗘𝗻𝗴𝗶𝗻𝗲𝗲𝗿𝗶𝗻𝗴 #𝗛𝗶𝗿𝗶𝗻𝗴 #𝗟𝗲𝗮𝗿𝗻𝗶𝗻𝗴
Solving Next Greater Element I with Stack and HashMap
More Relevant Posts
-
💫 Shallow Copy vs Deep Copy 💠 Shallow Copy: ▪️ Copies only the references of the objects, not the actual nested objects. ▪️ Both original and copied objects share the same memory reference for nested data. ▪️ Any changes made to the nested objects in one copy will affect the other. ✅ Faster but risky when data isolation is needed. 🔸 Deep Copy: ▪️ Creates a completely independent copy of the original object. ▪️ Nested objects are duplicated, so both copies work independently. ▪️ Changes in one copy do not affect the other. ⚙️ Slower but ensures data integrity and isolation. 👉 Shallow Copy = Shared references 👉 Deep Copy = Independent objects #Java #ShallowvsDeep #LearningJourney
To view or add a comment, sign in
-
-
🚀 Day 40 of #100DaysOfCode – LeetCode Problem #905: Sort Array By Parity 💡 Problem Summary: Given an integer array nums, move all even numbers to the front and all odd numbers to the back — return any valid ordering that satisfies this rule. 📘 Examples: Input: nums = [3,1,2,4] Output: [2,4,3,1] Explanation: Other valid answers include [4,2,3,1], [2,4,1,3]. 🧠 Approach: Create a new list to store results. First, add all even numbers. Then, add all odd numbers. Convert the list back to an array and return it. 💻 Java Solution: class Solution { public int[] sortArrayByParity(int[] nums) { List<Integer> arr = new ArrayList<>(); for (int num : nums) { if (num % 2 == 0) arr.add(num); } for (int num : nums) { if (num % 2 != 0) arr.add(num); } int[] array = new int[arr.size()]; for (int i = 0; i < arr.size(); i++) { array[i] = arr.get(i); } return array; } } ⚙️ Complexity: Time: O(n) Space: O(n) ✅ Result: Accepted (Runtime: 0 ms) 🎯 Key Takeaway: Sometimes, a problem doesn’t need a complex algorithm — just logical iteration and clean organization of data. Simple can still be powerful.
To view or add a comment, sign in
-
🌟 Day 28 of #100DaysOfCode 🌟 🔍 Reverse Words in a String — Clean & Elegant String Manipulation 🔹 What I Solved Today, I solved the classic “Reverse Words in a String” problem — a deceptively simple challenge that tests your understanding of string manipulation, trimming spaces, and efficient iteration. This problem is all about cleaning messy input and reordering data logically, which is a valuable skill in real-world text processing tasks. 📝 Problem Statement Given an input string s, reverse the order of the words. A word is defined as a sequence of non-space characters. The returned string should have only a single space separating words — with no leading or trailing spaces. Example 1: Input: s = "the sky is blue" Output: blue is sky the Example 2: Input: s = " hello world " Output: world hello Example 3: Input: s = "a good example" Output: example good a 🧠 Concepts Used String Splitting & Trimming Whitespace Handling Iteration & StringBuilder Efficient Memory Management ⚙️ Approach 1️⃣ Trim the string to remove extra leading/trailing spaces. 2️⃣ Split the string by one or more spaces using regex (\\s+). 3️⃣ Iterate backward through the words array. 4️⃣ Append words to a StringBuilder, adding spaces only between words. 5️⃣ Return the final reversed and clean string. 🚀 What I Learned This problem reinforced how attention to detail matters in coding — especially when handling strings and whitespace. It also reminded me that even simple problems can teach clean code principles, edge case thinking, and time-space optimization. Grateful to K.R. Mangalam University for continuously motivating me on this journey of learning and consistency. #100DaysOfCode #Java #ProblemSolving #CodingJourney #DataStructures #Algorithms
To view or add a comment, sign in
-
-
👉 LeetCode: 278. First Bad Version This one’s a classic binary search problem that tests how well you understand mid calculations and boundary updates. 👉 Problem: You’re given n versions of a product. One version is bad — and all versions after it are bad too. You need to find the first bad version using the given API isBadVersion(version). Here’s my implementation 👇 public class Solution extends VersionControl { public int firstBadVersion(int n) { int left = 1, right = n; int ans = -1; while (left <= right) { int mid = left + (right - left) / 2; if (isBadVersion(mid)) { right = mid - 1; ans = mid; } else { left = mid + 1; } } return ans; } } 👉 How it works (step by step): 1. Start with the full range from 1 to n. 2. Find the middle version mid. 3. If mid is bad → move left (there might be an earlier bad one). 4. Otherwise → move right. 5. Keep track of the last “bad” version found (ans). 6. When the loop ends, ans holds the first bad version. 👉 Time Complexity: O(log n) Because each check halves the search space. 👉 Space Complexity:O(1) Only a few integer variables are used, no extra data structures. This problem is a neat example of how binary search isn’t just for sorted arrays — it’s a mindset for narrowing down uncertainty efficiently. #LeetCode #Java #Coding #BinarySearch #ProblemSolving
To view or add a comment, sign in
-
🚀 Max-Heap Implementation (Data Structures And Algorithms) Max-heaps are crucial for scenarios needing quick access to the largest element. This Java code demonstrates how to create a max-heap using a PriorityQueue. The `PriorityQueue` is initialized with a custom comparator to ensure it behaves as a max-heap. The `add` and `poll` methods are used to insert elements and extract the maximum element, respectively. This example illustrates how to adapt the `PriorityQueue` class to implement a max-heap effectively. 💪 Build skills, build wealth, build your future! 🔥 Transform your learning — 10,000+ concepts, 4,000+ articles, 12,000+ questions. Smart. Fast. Personalized! 👇 Links available in the comments! #Algorithms #DataStructures #CodingInterview #ProblemSolving #professional #career #development
To view or add a comment, sign in
-
-
🔥 Day 122 of My DSA Challenge – Delete Node in a Linked List 🔷 Problem : 237. Delete Node in a Linked List 🔷 Goal : Delete a given node from a singly linked list — but without having access to the head of the list. 🔷 Key Insight : This is one of those classic Linked List interview questions that tests conceptual understanding over coding complexity. Normally, to delete a node, we need access to its previous node (to change the next pointer). But here, we’re not given the head — only the node that must be deleted. So how do we “delete” it? By using a clever trick — 👉 Copy the value of the next node into the current node. 👉 Then skip the next node (effectively deleting it). 🔷 Approach : 1️⃣ Overwrite the current node’s value with the value of its next node. 2️⃣ Link the current node’s next pointer to node.next.next. 3️⃣ This effectively removes the “next” node from the chain, achieving deletion without needing the head reference. Time Complexity: O(1) Space Complexity: O(1) This problem beautifully demonstrates data overwriting and pointer manipulation in linked lists. Sometimes, deleting isn’t about removing — it’s about replacing smartly. ⚡ Concepts reinforced : ✅ In-place modification ✅ Node manipulation ✅ Understanding memory links in Linked Lists Every concept — from arrays to linked lists — builds a deeper sense of logic and problem-solving clarity. #Day122 #DSA #100DaysOfCode #LeetCode #Java #LinkedList #ProblemSolving #Algorithms #DataStructures #CodingChallenge #DeveloperJourney #EngineerMindset #GrowEveryday #Learning
To view or add a comment, sign in
-
-
🚀 Day 43 of #100DaysOfCode – LeetCode Problem #2460: Apply Operations to an Array 💬 Problem Summary: You’re given a non-negative integer array nums. You need to: Sequentially check each element nums[i]. If nums[i] == nums[i + 1], then: Multiply nums[i] by 2 Set nums[i + 1] to 0 After all operations, move all zeros to the end of the array. Return the resulting array. 🧩 Example: Input: [1,2,2,1,1,0] Output: [1,4,2,0,0,0] Explanation: - i=1: 2 == 2 → [1,4,0,1,1,0] - i=3: 1 == 1 → [1,4,0,2,0,0] Shift zeros → [1,4,2,0,0,0] 🧠 Logic: ✅ Traverse the array once, applying the doubling rule. ✅ Use a two-pointer approach or list building to shift zeros efficiently. 💻 Java Solution: class Solution { public int[] applyOperations(int[] nums) { int n = nums.length; for (int i = 0; i < n - 1; i++) { if (nums[i] == nums[i + 1]) { nums[i] *= 2; nums[i + 1] = 0; } } int index = 0; for (int num : nums) { if (num != 0) nums[index++] = num; } while (index < n) { nums[index++] = 0; } return nums; } } ⚙️ Complexity: Time: O(n) Space: O(1) ✅ Result: Accepted (Runtime: 0 ms) 💬 Takeaway: This problem reinforces the importance of in-place transformations and efficient data movement.
To view or add a comment, sign in
-
💡 Linked List Series – Day 01 / 10 Welcome to 10-day beginner-friendly journey where we’ll master all Linked List concepts with clarity, code, and confidence 🚀 🔹 What is a Linked List? A Linked List is a linear data structure with a series of connected nodes in non-contiguous memory locations, a node contains: data — the value stored in the node next — a pointer/reference to the next node in the sequence It looks like this: 10 → 20 → 30 → null 🔹 Why Linked List? Unlike arrays, Linked Lists: ✅ Don’t need contiguous memory ✅ Allow easy insertion & deletion ✅ Can dynamically grow or shrink 🚫 But they don’t support random access like arrays In short: Use Linked List when frequent insertions/deletions are required. 🔹 How Linked List Works (in Java) class Node { // Structure of a node int data; // a node stores data as a 1st field Node next; // stores address of the next node as 2nd field Node(int data) { this.data = data; this.next = null; } } Each Node points to the next, forming a chain until the last node points to null. 🧭 Agenda of this Series: 1️⃣ Linked List Introduction 2️⃣ Display elements (Recursively & Iteratively) 3️⃣ Insert at Beginning 4️⃣ Insert at End 5️⃣ Insert at Middle 6️⃣ Delete at Beginning 7️⃣ Delete at End 8️⃣ Delete a Node 9️⃣ Search a Node, Update a Node, Find Length of Linked List 🔟 Linked List Interview Questions This series is perfect for beginners who find Linked Lists confusing — by the end, you’ll feel confident and ready to solve any DSA problem 💪 🔔 Follow the hashtag → #CodeWithLakkojuEswaraSai #CodeWithLakkojuEswaraSai_LinkedList #DataStructures #Java #Coding #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Day 42 of #100DaysOfCode – LeetCode Problem #1356: Sort Integers by The Number of 1 Bits 💬 Problem Summary: Given an integer array arr, sort the integers in ascending order by the number of 1’s in their binary representation. If two or more integers have the same number of 1’s, sort them in ascending numerical order. 🧩 Example: Input: arr = [0,1,2,3,4,5,6,7,8] Output: [0,1,2,4,8,3,5,6,7] Explanation: 0 -> 0 bits 1,2,4,8 -> 1 bit 3,5,6 -> 2 bits 7 -> 3 bits 🧠 Logic: ✅ Count the number of 1s in each number’s binary form. ✅ Sort by (1) number of 1s, then (2) value. 💡 Key trick: Use the bit manipulation technique num &= (num - 1) to count set bits efficiently. 💻 Java Solution: class Solution { public int[] sortByBits(int[] arr) { Arrays.sort(arr, (a, b) -> { int countA = countBits(a); int countB = countBits(b); if (countA == countB) return a - b; return countA - countB; }); return arr; } private int countBits(int num) { int count = 0; while (num > 0) { num &= (num - 1); count++; } return count; } } ⚙️ Complexity: Time: O(n log n) (due to sorting) Space: O(1) ✅ Result: Accepted (Runtime: 1 ms) 💬 Takeaway: This problem beautifully combines sorting logic with bitwise manipulation. It’s a reminder that knowing how data is represented at the binary level gives you powerful optimization tools
To view or add a comment, sign in
-
#100DaysOfCode – Day 66 String Manipulation & Primitive Decomposition 🧩 Task: Given a valid parentheses string, decompose it into its primitive components and then remove the outermost parentheses from each component. Example: Input: s = "(()())(())" Primitive Decomposition: "(()())" + "(())" After removing outermost parentheses: "()()" + "()" Output: "()()()" My Approach: I iterated through the string while keeping a counter to track the balance of open parentheses. When an opening parenthesis ( was found, I incremented the counter. If the count was greater than 1, it meant this parenthesis was not an outermost one, so I appended it to the result. When a closing parenthesis ) was found, I only appended it if the counter was greater than 1 before decrementing. This ensures the final closing parenthesis of a primitive part is excluded. This simple counter-based approach effectively identifies and removes the correct parentheses without needing a more complex data structure like a stack. Time Complexity: O(N) Space Complexity: O(N) Sometimes, a simple counter is all you need to elegantly handle nested structures. It can be a clean and efficient alternative to more complex data structures for certain problems. #takeUforward #100DaysOfCode #Java #ProblemSolving #LeetCode #DataStructures #Algorithms #StringManipulation #CodeNewbie
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