Day 28 Problem Statement: Given an array arr[] of postive and negative integers, the objective is to find the number of subarrays having a sum exactly equal to a given number k. Examples: Input : arr[] = [10, 2, -2, -20, 10], k = -10 Output : 3 Explanation: Subarrays: arr[0...3], arr[1...4], arr[3...4] have sum equal to -10. Input : arr[] = [9, 4, 20, 3, 10, 5], k = 33 Output : 2 Explanation: Subarrays: arr[0...2], arr[2...4] have sum equal to 33. Input : arr[] = [1, 3, 5], k = 2 Output : 0 Explanation: No subarrays with 0 sum. Approach : To count subarrays with sum k, we use a hash map to store the frequency of prefix sums. At each index, we calculate the current prefix sum currSum and check if (currSum - k) exists in the map. If it does, it means there are subarrays ending at the current index with sum k, and we add their count to the result. Then we update the frequency of currSum in the map. #HappyCoding #DSA #java #hashing
Counting Subarrays with Sum K in Java
More Relevant Posts
-
Day 25 - Search Insert Position Technique Used: Binary Search Key Idea: Applied binary search to locate the target in a sorted array. If the target is not found, returned the index where it would be inserted while maintaining sorted order. The final start pointer represents the correct insertion position. Time Complexity: O(log n) #Day25 #LeetCode #Java #BinarySearch #DSA #Algorithms
To view or add a comment, sign in
-
-
💻 Day 6 of #30DaysOfCodeChallenge Today’s problem: Reverse a String 🔹 Objective: Take an input string and reverse it. 🔹 Skills practiced: String manipulation, loops, basic algorithm 🔹 Key takeaway: Understanding string traversal and building logic from scratch strengthens your problem-solving skills. Example: Input: "Chetan" → Output: "natehC" ✅ Simple, but reinforces algorithmic thinking and attention to detail. #CodingChallenge #DSA #Java #ProblemSolving #100DaysOfCode
To view or add a comment, sign in
-
-
𝗗𝗮𝘆 𝟮𝟬/𝟮𝟬 — 𝗟𝗲𝗲𝘁𝗖𝗼𝗱𝗲 𝗖𝗵𝗮𝗹𝗹𝗲𝗻𝗴𝗲 Solved 3Sum using Sorting + Two Pointer technique. ➤ Approach (O(n²), O(1) extra space apart from result): • First, sort the array • Fix one element i • Use two pointers (left, right) to find pairs such that --> nums[i] + nums[left] + nums[right] == 0 • Move pointers based on whether the sum is smaller or larger than zero • Store unique triplets ➤ Key Insight: Sorting simplifies the problem. Once sorted, the two-pointer technique efficiently avoids checking every combination. Brute force would be O(n³). Optimized approach reduces it to O(n²). #LeetCode #Java #DSA #TwoPointers #Sorting #ProblemSolving #20DaysChallenge #Consistency
To view or add a comment, sign in
-
-
𝗗𝗮𝘆 𝟳/𝟮𝟬 — 𝗟𝗲𝗲𝘁𝗖𝗼𝗱𝗲 𝗖𝗵𝗮𝗹𝗹𝗲𝗻𝗴𝗲🎯 Solved Longest Valid Parentheses ➤ Problem: Given a string of ‘(’ and ‘)’, determine the length of the longest well-formed (valid) parentheses substring. ➤ Approach: Used a clean and structured stack-based technique to identify valid boundaries efficiently. • Initialize the stack with -1 as the base index. • Push every '(' index onto the stack. • On encountering ')', pop to attempt a match. • If the stack becomes empty, push the current index as the new starting point. • Otherwise, compute the valid substring length using currentIndex − stackTop. Continuously update the maximum length. This ensures each character is processed in a single pass, maintaining optimal efficiency. #LeetCode #Java #DSA #TwoPointers #ArrayManipulation #ProblemSolving #20DaysChallenge #Consistency
To view or add a comment, sign in
-
-
Today I worked on a fun little pattern-checking problem in Java: detecting a “trionic” array — one that goes: strictly increasing ➝ strictly decreasing ➝ strictly increasing What I like about this solution is that it’s clean, fast, and doesn’t overcomplicate things with extra arrays or nested loops. It simply walks the array once, identifying the turning points: p = peak of the first increasing run q = bottom after the decreasing run flag = end of the final increasing run And then validates that: ✅ all three phases exist ✅ each phase has at least one step ✅ the last phase reaches the end of the array Time complexity: O(n) Space complexity: O(1) Leetcode problem link:https://lnkd.in/g8nkhR85 #Java #DSA #Algorithms #CodingInterview #ProblemSolving #SoftwareEngineering
To view or add a comment, sign in
-
-
#Coding4 Q: Check whether a given array is sorted in ascending order. Example: {1, 3, 5, 7, 9} → ✅ Sorted {1, 5, 3, 7} → ❌ Not Sorted I explored 3 different approaches: ✅ 1. Single Pass (Optimal – O(n)) static boolean isSorted(int[] arr) { for(int i = 0; i < arr.length - 1; i++) { if(arr[i] > arr[i + 1]) return false; } return true; } ✅ 2. Using Streams boolean sorted = IntStream.range(0, arr.length - 1).allMatch(i -> arr[i] <= arr[i + 1]); ✅ 3. Compare with Sorted Copy int[] copy = arr.clone(); Arrays.sort(copy); boolean isSorted = Arrays.equals(copy, arr); Key Learnings: Single-pass solution is interview preferred (O(n), O(1)) Streams provide a functional style Sorting approach is simpler but less optimal Practicing fundamentals daily to strengthen problem-solving skills #DSA #Java #Arrays #ProblemSolving #CodingJourney #InterviewPrep #LearningInPublic #LinkedInDSA
To view or add a comment, sign in
-
#Coding9 Q: Move Zeros to the End (Two Pointer Technique – Java) Example: int[] arr = {0, 1, 0, 3, 12}; Output → {1, 3, 12, 0, 0} ✅ Two Pointer Technique (Optimal – O(n), O(1)) static void moveZeros(int[] arr) { int j = 0; // position to place next non-zero for(int i = 0; i < arr.length; i++) { if(arr[i] != 0) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; j++; } } } How It Works i scans the entire array j tracks where the next non-zero should go When a non-zero is found → swap with index j Zeros automatically move toward the end Complexity Analysis • Time Complexity → O(n) • Space Complexity → O(1) (In-place solution) This approach is interview-preferred because it is efficient and preserves order. #DSA #Java #Arrays #TwoPointers #ProblemSolving #InterviewPrep #LearningInPublic #LinkedInDSA
To view or add a comment, sign in
-
📝 Day 19/30 – LeetCode #33 (Search in Rotated Sorted Array) | Java This problem combines binary search with array rotation, making it more about logic than syntax. The main challenge was identifying which half of the array is sorted at every step and deciding whether the target lies within that range. By comparing boundary values and narrowing the search space accordingly, the problem can be solved efficiently in O(log n) time. This reinforced how adaptable binary search becomes when combined with careful condition checks. Another reminder that mastering patterns is far more important than memorizing solutions. #LeetCode #Java #DSA #BinarySearch #Arrays #ProblemSolving #LearningInPublic
To view or add a comment, sign in
-
-
#Coding7 Q: Rotate an Array (Java) Example: int[] arr = {1, 2, 3, 4, 5, 6, 7} k = 3 Output → {5, 6, 7, 1, 2, 3, 4} I explored 3 different approaches: ✅ 1. Reverse Method (Optimal – O(n), O(1)) static void rotate(int[] arr, int k) { k = k % arr.length; reverse(arr, 0, arr.length - 1); reverse(arr, 0, k - 1); reverse(arr, k, arr.length - 1); } static void reverse(int[] arr, int l, int r) { while(l < r) { int temp = arr[l]; arr[l] = arr[r]; arr[r] = temp; l++; r--; } } ✅ 2. Using Extra Array (O(n) space) int n = arr.length; int[] temp = new int[n]; for(int i = 0; i < n; i++) { temp[(i + k) % n] = arr[i]; } arr = temp; ✅ 3. Brute Force Approach (O(n × k)) for(int i = 0; i < k; i++) { int last = arr[arr.length - 1]; for(int j = arr.length - 1; j > 0; j--) { arr[j] = arr[j - 1]; } arr[0] = last; } Key Learnings: Reverse method is interview preferred (in-place, no extra memory) Extra array approach is easier but uses additional space Brute force works but is inefficient for large k #DSA #Java #Arrays #ProblemSolving #CodingJourney #InterviewPrep #LearningInPublic #LinkedInDSA
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