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
Solved Range Sum Query in Java using Prefix Sum technique
More Relevant Posts
-
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
To view or add a comment, sign in
-
-
🔢 Today I worked on a classic matrix problem in Java — Diagonal Sum. The goal was simple: Calculate the sum of both the primary and secondary diagonals of a square matrix. Initially, I used a nested loop approach with O(n²) complexity. But then I optimized it to a clean O(n) solution by directly accessing diagonal indexes. While optimizing, I made an interesting mistake: ❌ I wrote if (i != matrix[i][matrix.length - 1 - i]) Here I accidentally compared an index with an element value. ✔ Correct approach: if (i != matrix.length - 1 - i) This ensures the center element in odd-sized matrices isn’t counted twice. 🧠 Key Learning: Indexes and values may look similar, but mixing them can break logic silently. Optimization is not just about speed — it’s about accuracy. #Java #leetcode #Coding #DSA #ProblemSolving #LearningInPublic #SoftwareEngineering
To view or add a comment, sign in
-
-
Day 91 of #100DaysOfCode Solved Base 7 in Java 🔢 Approach The challenge was to convert a given integer (num) to its base 7 string representation. Conversion Method The core of the solution lies in the standard algorithm for base conversion: repeated division and remainder collection. Handle Zero and Negatives: If the input num is 0, the result is immediately "0". I determined if the number is negative and stored this in a boolean flag, then proceeded with the absolute value of the number (num = Math.abs(num)) for the conversion logic. Conversion Loop: I used a while loop that continues as long as num > 0. In each iteration: The remainder when num is divided by 7 (num % 7) gives the next digit in base 7. This digit is appended to a StringBuilder. num is then updated by integer division by 7 (num /= 7). Final Result: Since the remainders are collected in reverse order, I called sb.reverse(). If the original number was negative, I prepended a hyphen (-) to the reversed string. Finally, I returned the result as a string. This simple and efficient implementation had a very fast runtime, beating 77.39% of submissions. #Java #100DaysOfCode #LeetCode #CodingChallenge #Algorithms #BaseConversion #ProblemSolving
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 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
-
-
Day 89 of #100DaysOfCode Solved Find Numbers with Even Number of Digits in Java 🔢 Approach The goal of this problem was to count how many integers in a given array have an even number of digits. I implemented two methods: findNumbers(int[] nums): This is the main function that iterates through every number in the input array nums. isEvenOrOdd(int n): This helper function takes an integer and determines if its digit count is even or odd. Inside the helper function, I used a while loop to count the digits: I initialized a count to 0. The loop continues as long as $n > 0$. In each iteration, I increment count and then perform integer division by 10 (n = n / 10) to remove the least significant digit. Finally, I return true if the total count of digits is even (count \% 2 == 0). This efficient, digit-by-digit checking approach resulted in a strong performance, beating 98.90% of other submissions. #Java #100DaysOfCode #LeetCode #CodingChallenge #Algorithms #Array #ProblemSolving #Optimization
To view or add a comment, sign in
-
-
🔥 LeetCode Day--- 4 | “Median of Two Sorted Arrays” (Hard, Java) Today’s challenge was one of those that really test your logic, patience, and understanding of binary search. This problem wasn’t about just merging two sorted arrays — it was about thinking smarter 🧠. Instead of brute-forcing through both arrays (O(m+n)), I implemented a binary partition approach to achieve O(log(min(m, n))) efficiency 💡 What I learned today: Always choose the smaller array for binary search — it makes the partition logic simpler. Handle boundaries carefully with Integer.MIN_VALUE and Integer.MAX_VALUE. The goal is to find the perfect partition where: Left half ≤ Right half Elements are balanced across both arrays Once that’s done → median can be easily calculated! ✅ Result: Accepted | Runtime: 0 ms 🚀 Hard problem turned into a logic puzzle that was actually fun to solve! 🧩 Concepts Strengthened: Binary Search Partitioning Logic Edge Case Handling Mathematical Thinking #LeetCode #Day4 #Java #BinarySearch #ProblemSolving #CodingChallenge #DataStructures #Algorithms #CodeEveryday #DeveloperJourney #TechLearning #LeetCodeHard #CodingCommunity
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