Day 80 of #100DaysOfCode Solved Frequency Sort in Java 🔠 Approach Today's problem was to sort an array based on the frequency of its numbers. My initial solution was accepted, but it exposed a major efficiency gap! My strategy involved: Sorting the array first. Using nested loops to count the frequency of each number and store it in a HashMap. (Implied) Using the counts to perform the final custom sort. The core issue was the counting method: running a full loop inside another full loop to get the frequency. This quadratic $O(N^2)$ counting completely tanked the performance. ✅ Runtime: 29 ms (Beats 12.02%) ✅ Memory: 45.26 MB (Beats 5.86%) Another great lesson in algorithmic complexity! The difference between $O(N^2)$ and the optimal $O(N \log N)$ for this problem is massive. Time to refactor and implement the fast, single-pass $O(N)$ frequency count using getOrDefault! 💪 #Java #100DaysOfCode #LeetCode #CodingChallenge #Algorithms #Arrays #HashMap #Optimization #ProblemSolving
Improved Frequency Sort in Java with O(N) Counting
More Relevant Posts
-
Day 85 of #100DaysOfCode Solved Range Sum Query - Immutable (NumArray) in Java ➕ Approach Today's problem was a classic that demonstrates the power of pre-computation: finding the sum of a range in an array many times. The optimal solution is the Prefix Sum technique. Pre-computation: In the constructor, I built a prefixSum array where prefixSum[i] holds the sum of all elements from index 0 up to index $i-1$ in the original array. This takes $O(N)$ time. $O(1)$ Query: The magic happens in the sumRange(left, right) method. The sum of any range $[left, right]$ is found instantly by calculating prefixSum[right + 1] - prefixSum[left]. The cost of a single $O(N)$ setup is outweighed by the ability to perform every subsequent query in $O(1)$ time! #Java #100DaysOfCode #LeetCode #CodingChallenge #Algorithms #Arrays #PrefixSum #Optimization #ProblemSolving
To view or add a comment, sign in
-
-
Day 90 of #100DaysOfCode Solved Squares of a Sorted Array in Java 🔠 Approach The task was to take an array of integers sorted in non-decreasing order, square each number, and then return the result array also sorted in non-decreasing order. Brute-Force Method The solution implemented here is a straightforward two-step brute-force approach: Squaring: I iterated through the input array nums and replaced each element with its square (i.e., nums[i] * nums[i]). This handles both positive and negative numbers correctly. Sorting: After squaring all elements, I used Java's built-in Arrays.sort(nums) method to sort the entire array. While correct, this approach has a time complexity dominated by the sorting step, which is O(NlogN), where N is the number of elements. The runtime of 10 ms shows that a more efficient, two-pointer approach (which can solve this in O(N) time) is generally preferred for optimal performance. #Java #100DaysOfCode #LeetCode #CodingChallenge #Algorithms #Array #Sorting #ProblemSolving
To view or add a comment, sign in
-
-
LeetCode Question #199 — Binary Tree Right Side View Thrilled to share another Accepted Solution (100% Runtime 🚀) on LeetCode! This problem focuses on Binary Trees — specifically, how to capture the view of a tree from its right side 🌳➡️. I implemented a Modified Pre-Order Traversal (Root → Right → Left) in Java, ensuring that the first node at each level (from the right) gets recorded. 💡 Key Idea: Use recursion with a level tracker — when the current level equals the list size, it means we’re seeing the rightmost node for the first time. Here’s the performance snapshot: ⚙️ Runtime: 0 ms (Beats 100% of Java submissions) 💾 Memory: 42.4 MB Every problem like this sharpens my understanding of tree traversal patterns and depth-first search optimization. #LeetCode #Java #DataStructures #BinaryTree #ProblemSolving #CodingJourney #DSA #100PercentRuntime
To view or add a comment, sign in
-
-
📌 Day 16/100 - Reverse String (LeetCode 344) 🔹 Problem: Reverse a given string in-place — meaning you must modify the original array of characters without using extra space. 🔹 Approach: Used the two-pointer technique — one starting at the beginning and one at the end of the array. Swap characters at both pointers, then move them closer until they meet. Efficient, clean, and runs in linear time without additional memory allocation. 🔹 Key Learnings: In-place algorithms optimize space complexity significantly. The two-pointer pattern is a versatile tool for many array and string problems. Understanding mutable vs immutable structures in Java is crucial for memory efficiency. Sometimes, the simplest logic beats the most complex one. 🧠 “True efficiency lies in simplicity, not complexity.” #100DaysOfCode #LeetCode #Java #ProblemSolving #DSA #CodingJourney #TwoPointers
To view or add a comment, sign in
-
-
🚀 Day 55 of #100DaysOfCode Challenge Problem: LeetCode #219 – Contains Duplicate II Language: Java ☕ Today I solved an interesting array problem that checks whether a duplicate element exists within a given distance k in the array. 💡 Logic: Use a HashMap to remember the last index of each number. If the same number appears again, check if the difference between indices ≤ k. If yes → return true, else keep checking. 💻 Code: import java.util.HashMap; public class Solution { public boolean containsNearbyDuplicate(int[] nums, int k) { HashMap<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { if (map.containsKey(nums[i]) && i - map.get(nums[i]) <= k) { return true; } map.put(nums[i], i); } return false; } } 🧠 Example: Input: [1,2,3,1], k = 3 Output: true ✅ (same number 1 appears within distance 3) ⚙️ Key Concepts: HashMap for quick lookup Difference check using indices Time Complexity → O(n) Space Complexity → O(n) 💬 Every day’s problem teaches me something new — today it was about using maps smartly to track elements efficiently. On to the next challenge! 💪 #Day55 #LeetCode #Java #100DaysOfCode #CodingJourney #ProblemSolving #HashMap #DSA
To view or add a comment, sign in
-
-
🚀 Day 55 of #100DaysOfCode Challenge Problem: LeetCode #219 – Contains Duplicate II Language: Java ☕ Today I solved an interesting array problem that checks whether a duplicate element exists within a given distance k in the array. 💡 Logic: Use a HashMap to remember the last index of each number. If the same number appears again, check if the difference between indices ≤ k. If yes → return true, else keep checking. 💻 Code: import java.util.HashMap; public class Solution { public boolean containsNearbyDuplicate(int[] nums, int k) { HashMap<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { if (map.containsKey(nums[i]) && i - map.get(nums[i]) <= k) { return true; } map.put(nums[i], i); } return false; } } 🧠 Example: Input: [1,2,3,1], k = 3 Output: true ✅ (same number 1 appears within distance 3) ⚙️ Key Concepts: HashMap for quick lookup Difference check using indices Time Complexity → O(n) Space Complexity → O(n) 💬 Every day’s problem teaches me something new — today it was about using maps smartly to track elements efficiently. On to the next challenge! 💪 #Day55 #LeetCode #Java #100DaysOfCode #CodingJourney #ProblemSolving #HashMap #DSA
To view or add a comment, sign in
-
-
🚀 Day 55 of #100DaysOfCode Challenge Problem: LeetCode #219 – Contains Duplicate II Language: Java ☕ Today I solved an interesting array problem that checks whether a duplicate element exists within a given distance k in the array. 💡 Logic: Use a HashMap to remember the last index of each number. If the same number appears again, check if the difference between indices ≤ k. If yes → return true, else keep checking. 💻 Code: import java.util.HashMap; public class Solution { public boolean containsNearbyDuplicate(int[] nums, int k) { HashMap<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { if (map.containsKey(nums[i]) && i - map.get(nums[i]) <= k) { return true; } map.put(nums[i], i); } return false; } } 🧠 Example: Input: [1,2,3,1], k = 3 Output: true ✅ (same number 1 appears within distance 3) ⚙️ Key Concepts: HashMap for quick lookup Difference check using indices Time Complexity → O(n) Space Complexity → O(n) 💬 Every day’s problem teaches me something new — today it was about using maps smartly to track elements efficiently. On to the next challenge! 💪 #Day55 #LeetCode #Java #100DaysOfCode #CodingJourney #ProblemSolving #HashMap #DSA
To view or add a comment, sign in
-
-
🚀 Day 18/100 of #100DaysOfCode ✅ Solved “Isomorphic Strings” (LeetCode #205) using Java! 🧩 Problem: Given two strings s and t, determine if they are isomorphic. 👉 Two strings are isomorphic if characters in one string can be replaced to get the other — while keeping order and unique mapping intact. 🧠 Approach: Used a HashMap to store the mapping of characters from s → t. Checked if each character in s has a consistent mapping in t. Also ensured that no two characters in s map to the same character in t. ✨ Example: s = "egg", t = "add" → true (e→a, g→d) s = "foo", t = "bar" → false 📈 Complexity: Time: O(n) Space: O(n) 💡 Key Learnings: Understood how to maintain one-to-one character mapping using a HashMap. Reinforced logic building for pattern matching between strings. 💻 Tech Used: Java | HashMap | Problem Solving #LeetCode #100DaysOfCode #Java #ProblemSolving #DSA #CodingJourney #LearnByDoing #DevCommunity
To view or add a comment, sign in
-
-
🌳 Day 65 of #LeetCode Journey 🔹 Problem: 106. Construct Binary Tree from Inorder and Postorder Traversal 🔹 Difficulty: Medium 🔹 Language: Java Today’s problem is about rebuilding a binary tree when you’re given its inorder and postorder traversal arrays. 🧩 Key Idea: The last element in postorder is always the root. In inorder traversal, elements to the left of the root are in the left subtree, and elements to the right are in the right subtree. We recursively build the tree using this property. 💡 Approach: Start from the end of the postorder array to get the root. Use a hashmap to store inorder indices for O(1) lookup. Recursively construct the right subtree first, then the left subtree (since we’re moving backward in postorder). 🧠 Concepts reinforced: Recursion HashMap for index lookup Understanding inorder & postorder relationships 🔥 Another step forward in mastering tree construction problems! #LeetCode #100DaysOfCode #Java #CodingChallenge #DataStructures #BinaryTree #Recursion #ProblemSolving #ProgrammingJourney
To view or add a comment, sign in
-
-
✅ Day 35 of #100DaysOfCode Challenge 📘 LeetCode Problem 112: Path Sum 🧩 Problem Statement: Given the root of a binary tree and an integer targetSum, return true if there exists a root-to-leaf path whose sum of node values equals targetSum. Example: Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22 Output: true Explanation: Path 5 → 4 → 11 → 2 gives the sum = 22 ✅ 💡 Simple Approach: If the tree is empty → return false If it’s a leaf node → check if its value equals targetSum Otherwise → subtract node value and check left and right recursively 💻 Easiest Java Code: class Solution { public boolean hasPathSum(TreeNode root, int sum) { if (root == null) return false; if (root.left == null && root.right == null && root.val == sum) return true; sum = sum - root.val; return hasPathSum(root.left, sum) || hasPathSum(root.right, sum); } } ⚙️ Complexity: ⏱️ Time: O(n) → visit each node once 💾 Space: O(h) → recursion stack (h = height of tree) 🌿 Small code, big concept — recursion makes trees easy 🌱 #Day35 #100DaysOfCode #LeetCode #Java #DSA #BinaryTree #Recursion #CodingChallenge
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