𝐒𝐨𝐥𝐯𝐞𝐝: 𝐄𝐯𝐚𝐥𝐮𝐚𝐭𝐞 𝐑𝐞𝐯𝐞𝐫𝐬𝐞 𝐏𝐨𝐥𝐢𝐬𝐡 𝐍𝐨𝐭𝐚𝐭𝐢𝐨𝐧 (𝐋𝐞𝐞𝐭𝐂𝐨𝐝𝐞 #𝟏𝟓𝟎) Today I solved the 𝐄𝐯𝐚𝐥𝐮𝐚𝐭𝐞 𝐑𝐞𝐯𝐞𝐫𝐬𝐞 𝐏𝐨𝐥𝐢𝐬𝐡 𝐍𝐨𝐭𝐚𝐭𝐢𝐨𝐧 problem, a classic stack-based question that strengthens understanding of data structures and expression evaluation. 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 𝐒𝐮𝐦𝐦𝐚𝐫𝐲: Given an array of strings representing an arithmetic expression in Reverse Polish Notation (RPN), evaluate and return the result. ✔ Operators: +, -, *, / ✔ Division truncates toward zero ✔ Valid RPN expression (no division by zero) 𝐊𝐞𝐲 𝐂𝐨𝐧𝐜𝐞𝐩𝐭: Stack Data Structure Why Stack? Because RPN works on the principle of: Push operands onto the stack When an operator appears → pop last two operands → apply operation → push result back This follows LIFO (Last In, First Out) behavior perfectly. 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡: Traverse each token. If it’s a number → push to stack. If it’s an operator: Pop top two elements Perform operation Push result back Final remaining value in stack = answer Time Complexity: O(n) Space Complexity: O(n) Example: Input → ["2","1","+","3","*"] Output → 9 Explanation → ((2 + 1) * 3) #LeetCode #DataStructures #Java #CodingInterview #ProblemSolving
Reverse Polish Notation Evaluation Solution
More Relevant Posts
-
🚀 Day 13 — Group Anagrams Continuing the Strings pattern. 🧩 Problem solved: Group Anagrams 💻 Platform: LeetCode (#49) Given an array of strings, group the words that are anagrams of each other. Example: Input: ["eat","tea","tan","ate","nat","bat"] Output: ["eat","tea","ate"] ["tan","nat"] ["bat"] --- 🧠 First Thought (Brute Force) Compare every word with every other word and check if they are anagrams. But this leads to O(n² × k log k) complexity. Clearly inefficient. --- ⚡ Optimal Approach — HashMap + Sorted Key Key Insight: All anagrams become identical after sorting. Example: eat → aet tea → aet ate → aet Steps: • Sort each word • Use the sorted word as a key • Store original words in a HashMap Finally return all grouped values. Time Complexity: O(n × k log k) Space Complexity: O(nk) --- 🔍 What this problem reinforced: ✔ Sorting can normalize strings ✔ HashMap helps group related data ✔ Anagram problems often rely on frequency or sorting patterns Recognizing patterns is becoming faster with daily practice. Day-13 complete. #DSA #Java #LeetCode #Strings #ProblemSolving #CodingJourney #LearningInPublic
To view or add a comment, sign in
-
-
I'm excited to share that my article on Baeldung has just been published: "JSON, TOON, and Java Format Libraries." The article covers how json-io handles three serialization formats — JSON, JSON5, and TOON — and compares it with Jackson, Gson, and JToon. The part I'm most excited about is TOON (Token-Oriented Object Notation). If you're building LLM-powered applications, you're paying for every token in your context window. TOON reduces token usage by 40-50% compared to JSON by eliminating braces, brackets, commas, and unnecessary quoting. Same data, dramatically fewer tokens. json-io also ships with a Spring Boot starter and a Spring AI module, so integrating TOON into existing Spring applications is straightforward. If you're working with Java and AI/LLM systems, I'd love to hear your thoughts. Article: https://lnkd.in/gXvAE3GW GitHub: https://lnkd.in/gxRn9-aC TOON spec: https://toonformat.dev #Java #JSON #TOON #LLM #AI #SpringBoot #OpenSource #Serialization
To view or add a comment, sign in
-
🌳 Day 28/30 – Validate Binary Search Tree (BST) Today’s problem focused on validating whether a binary tree satisfies the properties of a Binary Search Tree (BST) — a fundamental concept in tree-based data structures. 🧠 Problem Insight A Binary Search Tree must follow: All nodes in the left subtree < root All nodes in the right subtree > root This rule must hold recursively for every node, not just immediate children ⚙️ Approach I used a recursive DFS approach with range validation: Each node is assigned a valid range (min, max) Initially → (-∞, +∞) While traversing: Left subtree → update max = current node value Right subtree → update min = current node value If any node violates the range → it is not a valid BST 💡 Key Logic Instead of just checking: ❌ left < root < right (only local check) We ensure: ✅ Every node respects its global constraints using min-max bounds ⏱ Complexity Time Complexity: O(n) Space Complexity: O(h) (recursion stack) 📊 Performance ✅ All test cases passed ⚡ Beats 100% in runtime 🧩 Pattern Pattern: Tree + DFS + Range Validation 🎯 Interview Importance This problem is frequently asked and helps in understanding: ✔ Tree traversal (DFS) ✔ Recursion with constraints ✔ Validating global properties in trees It is also a base for problems like: Lowest Common Ancestor BST operations (insert/delete/search) Tree-based validations 📈 Growth Reflection This problem improved my understanding that: Tree problems are not just about traversal — they are about maintaining correct constraints during recursion. That mindset shift is key for solving advanced tree problems 💪 ✅ Day 28 completed. #Day28 #30DaysOfCode #LeetCode #BinaryTree #BST #DFS #Recursion #Java #CodingInterview #ProblemSolving #TechGrowth
To view or add a comment, sign in
-
-
Day - 30 Daily DSA Update Solved: Merge Sorted Array (LeetCode) Today’s problem focused on merging two sorted arrays into one sorted array while modifying the first array in-place. Problem: Given two sorted arrays nums1 and nums2, merge them into a single sorted array stored inside nums1. The first array has enough extra space at the end to accommodate elements from the second array. Approach: Instead of merging from the beginning, I used a two-pointer approach starting from the end of both arrays. • One pointer for the last valid element in nums1 • One pointer for the last element in nums2 • One pointer to place the largest element at the end of nums1 By comparing elements from the back, the larger element is placed at the correct position and pointers move backward. This avoids overwriting elements in nums1. Key Learning: Starting from the end can simplify in-place array problems and prevent unnecessary shifting of elements. What this strengthened: • Two pointer technique • In-place array manipulation • Efficient merging logic • Thinking about optimal traversal direction Each problem continues to strengthen my understanding of core data structures and algorithms. #DSA #DataStructures #Algorithms #Java #LeetCode #Arrays #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
Day 3 — DSA Practice Missed posting yesterday, but the consistency is still going strong. Solved 2 problems: • Two Sum II (Sorted Array)-167 Solved it in two ways: -Using HashMap -Using the Two Pointer approach It was interesting to compare both approaches. While HashMap works well, since the array is already sorted, the two-pointer method is cleaner and more space efficient. Time Complexity: -HashMap approach → O(n) time, O(n) space -Two Pointer approach → O(n) time, O(1) space Two pointers clearly felt more optimal here. • Number of Steps to Reduce a Number (Binary Representation) to One-1404 Initially, I tried converting the binary string using parseInt() and parseLong(), but it kept throwing overflow errors for large inputs. That made me realize that converting large binary strings directly isn’t always safe. Instead, I processed the string directly using: s.charAt(i) - '0' This avoids overflow and lets us simulate the operations efficiently. Time Complexity: -O(n), where n is the length of the binary string -O(1) extra space Key Takeaways: -Always consider constraints before choosing data types. -Sorted array problems often hint toward two-pointer solutions. -Small concepts (like converting char to int properly) can make a big difference. Learning > Just solving. Day 3 done. ✅ #DSA #Java #ProblemSolving #LearningInPublic #PlacementPreparation #Consistency
To view or add a comment, sign in
-
Most people would return this answer: [2, 2] But the correct answer is: [2] Why? 🚀 Day 64/365 — DSA Challenge Solved: Intersection of Two Arrays The task: Given two arrays, return their intersection. But there are two conditions: • The element must exist in both arrays • The result must contain only unique values Example: nums1 = [1,2,2,1] nums2 = [2,2] Output: [2] Even though 2 appears multiple times, it should appear only once in the result. 💡 My Approach (Simple Logic) Step 1 Loop through every element of nums1. Step 2 Check if that number exists in nums2. Step 3 Before adding it to the result, make sure it hasn't already been added. To keep the code clean, I used three methods: intersection() Main method that loops through nums1 and builds the result. existsInArray(num, arr) Checks if a number exists in another array. existsInArray(num, arr, length) Checks duplicates only inside the filled part of the result array. Example walkthrough: 1 -> not in nums2 -> skip 2 -> exists -> add 2 -> already added -> skip 1 -> skip Final output: [2] ⏱ Time Complexity: O(n × m) 📦 Space Complexity: O(n) Day 64/365 complete. Code 👇 https://lnkd.in/dad5sZfu #DSA #Java #LeetCode #LearningInPublic #ProblemSolving #Consistency
To view or add a comment, sign in
-
-
🚀 Day 517 of #750DaysOfCode 🔥 LeetCode 3666 – Minimum Operations to Equalize Binary String (Hard) Today’s problem was a parity + math-based greedy optimization challenge that looks simple at first glance but requires deep observation. 🧠 Problem Summary You are given: A binary string s An integer k In one operation, you must flip exactly k different indices. Goal: Make the entire string equal to '1' using the minimum number of operations. If impossible → return -1. 💡 Key Observations 1️⃣ Let zero = number of '0' in the string. 2️⃣ Each operation flips exactly k bits. 3️⃣ Flipping changes parity (even/odd behavior becomes important). 4️⃣ We must carefully handle: When k == length When parity of k and number of zeros mismatch When operations must be even or odd This becomes a mathematical bound + parity correction problem, not a brute-force simulation. 🛠️ Approach Used Count total zeros. Handle edge cases: If no zeros → answer = 0 If len == k → only one full flip possible Compute minimum operations for: Odd number of operations Even number of operations Adjust based on parity constraints. Return minimum valid answer. Time Complexity: O(n) Space Complexity: O(1) 🎯 What I Learned ✔️ Hard problems often reduce to mathematical constraints ✔️ Parity (even/odd) reasoning is powerful in bit-flip problems ✔️ Always check feasibility conditions before optimizing ✔️ Avoid brute force when constraints go up to 10⁵ This problem really tested logical thinking beyond implementation. On to Day 518 🚀 #LeetCode #Java #DataStructures #Algorithms #ProblemSolving #HardProblems #CodingJourney #750DaysOfCode
To view or add a comment, sign in
-
-
Reverse Integer – LeetCode Solution 📌 Problem Link Reverse Integer – LeetCode ⸻ 🧩 Problem Statement Given a signed 32-bit integer x, return the integer obtained by reversing its digits. If reversing x causes the value to go outside the signed 32-bit integer range [-2³¹, 2³¹ - 1], return 0. You must solve the problem without using 64-bit integers (long). ⸻ 💡 Approach To solve this problem: 1. Initialize a variable to store the reversed number. 2. Extract the last digit of the number using modulus operation. 3. Append the extracted digit to the reversed number. 4. Remove the last digit from the original number using division. 5. Before appending a digit, check for overflow and underflow conditions. 6. If overflow occurs, return 0. 7. Continue until the original number becomes 0. ⸻ ⚠️ Overflow Handling Since the integer range is limited to: • Minimum: -2147483648 • Maximum: 2147483647 Before multiplying the reversed number by 10 and adding a digit, we must verify: • It does not exceed Integer.MAX_VALUE • It does not go below Integer.MIN_VALUE If it exceeds the range, return 0. ⸻ 📊 Example Input: 123 Output: 321 Input: -123 Output: -321 Input: 1534236469 Output: 0 (Because it exceeds 32-bit integer range after reversing) ⸻ ⏱ Time Complexity O(log₁₀ n) • Because we process each digit once. 💾 Space Complexity O(1) • No extra space is used. ⸻ 🚀 Key Concepts Used • Modulus Operator • Integer Division • Overflow Checking • Looping • Basic Mathematics ⸻ 🏁 Conclusion This problem tests understanding of: • Digit manipulation • Edge case handling • Integer boundary conditions Proper overflow checking is the most important part of this solution. #java #dsa #javaprogram #dsaprogram #array #numbers #solution #leetcode #data #structure #algorithm
To view or add a comment, sign in
-
-
🚀 Day 40 / 100 – LeetCode Challenge Problem: Next Permutation (Medium) Today’s problem was about finding the next lexicographically greater permutation of a given integer array. 📌 Key Idea: Instead of generating all permutations, we efficiently transform the array to its next permutation using a smart approach. 🔹 Steps followed: 1. Traverse from the right to find the first element where nums[i] < nums[i+1]. 2.Find the next greater element to the right of nums[i]. 3. Swap these two elements. 4.Reverse the elements after index i to get the smallest possible order. 💡 If the array is in descending order, the next permutation becomes the ascending order. Time Complexity: O(n) Space Complexity: O(1) Concepts Practiced: Array manipulation Lexicographical ordering Two-pointer technique In-place operations Consistent progress towards mastering Data Structures & Algorithms 💪 #Day40 #100DaysOfCode #LeetCode #Java #DSA #CodingChallenge
To view or add a comment, sign in
-
-
Shrinking Data at the Bit Level: Building a Custom Huffman Compression Engine! I recently wanted to look under the hood of how files are actually stored on our hard drives, so I built a lossless File Compressor in Java from scratch. Instead of just simulating compression with strings of text, I engineered this to write raw, physically packed bytes to the disk. By analyzing character frequencies and assigning variable-length binary codes, this engine successfully reduces standard text file sizes by nearly 50%! The Technical Engine (Data Structures & Algorithms): Huffman Coding Algorithm: The core greedy algorithm that dynamically generates an optimal, prefix-free binary dictionary based on exact data frequencies. Priority Queue & Binary Trees: I utilized a PriorityQueue to efficiently extract minimum frequencies and build the Huffman Tree from the bottom up, maintaining an optimal O(NlogN) time complexity. Bitwise Manipulation: The most challenging and rewarding part! I used bit-shifting operations (<<, |) to pack eight '1's and '0's into a single physical Java byte. This ensures the .bin output file legitimately consumes less physical SSD space. Lossless Decompression: Built the exact reverse tree-traversal logic to perfectly reconstruct the original file without losing a single character. It is one thing to learn about Data Structures in theory, but seeing an actual .txt file physically shrink on your local drive is incredibly satisfying. Check out the full source code and my bitwise I/O utility on GitHub: https://lnkd.in/d3GiJUSG #Java #Algorithms #DataCompression #SoftwareEngineering #DataStructures #ComputerScience
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
☑️👍🏻