Skip to content

Commit

Permalink
add: prefix sum
Browse files Browse the repository at this point in the history
  • Loading branch information
thutasann committed Feb 16, 2025
1 parent 616cf53 commit b0cd4eb
Show file tree
Hide file tree
Showing 8 changed files with 229 additions and 0 deletions.
1 change: 1 addition & 0 deletions data_structures/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ This section contains Data Structure and Algorithms in Java, Typescript and Fron
- [Data Structures](./src/DataStructures)
- [Algorithms](./src/Algorithms)
- [Sliding Window](./src/KeyPatterns/SlidingWindow/README.md)
- [Prefix](./src/KeyPatterns/Prefix/README.md)
- [NeetCode 150](./neetcode_150/)
- [Javascript Questions](./js_questions)

Expand Down
70 changes: 70 additions & 0 deletions data_structures/neetcode_150/src/ProductOfArrayExceptSelf.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package neetcode_150.src;

import java.util.Arrays;

/**
* Product of Array Except Self
*
* @apiNote
* - Given an intger array `nums`, return an array such that
* `answers[i]` is equal to the product of all the elements of `nums`
* except `nums[i]`
* - The product of any prefix or suffix of nums is guaranteed to fit
* in a 32-bit integer.
* - You must write an algorithm that runs in `O(n)` time and without
* using the division operation.
* @example
* - Inputs: nums = [1 , 2, 3, 4]
* - Output: [24, 12, 8, 6]
* @explain
* - index | nums[i] | product of all elements except nums[i]
* - 0 | 1 | 2 * 3 * 4 = 24
*/
public class ProductOfArrayExceptSelf {
public static void main(String[] args) {
int[] nums = { 1, 2, 3, 4 };
System.out.println("Brute Force ==> " + Arrays.toString(bruteForce(nums)));
System.out.println("Prefix PostFix ==> " + Arrays.toString(productExceptSelf(nums)));
}

private static int[] productExceptSelf(int[] nums) {
int n = nums.length;
int[] result = new int[n];
Arrays.fill(result, 1);

int pre = 1, post = 1;

for (int i = 0; i < n; i++) {
result[i] = pre;
pre *= nums[i];
}

for (int i = n - 1; i >= 0; i--) {
result[i] *= post;
post *= nums[i];
}

return result;
}

/**
* Brute Force Approach (Incorrect Approach)
*/
private static int[] bruteForce(int[] nums) {
System.out.println("\nBrute Force Approach ==> ");
int n = nums.length;
int[] ans = new int[n];

for (int i = 0; i < n; i++) {
int product = 1;
for (int j = 0; j < n; j++) {
if (i != j) {
product *= nums[j];
}
}
ans[i] = product;
}

return ans;
}
}
37 changes: 37 additions & 0 deletions data_structures/neetcode_150/src/TopKFrequentElement.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
package neetcode_150.src;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;

/**
* Top K Frequent Elements
*
Expand All @@ -17,6 +23,37 @@
*/
public class TopKFrequentElement {
public static void main(String[] args) {
System.out.println("\nTop K Frequent Element ==> ");
int[] nums = { 1, 1, 1, 2, 2, 3 };
int k = 2;
System.out.println(Arrays.toString(topKFrequent(nums, k)));
}

private static int[] topKFrequent(int[] nums, int k) {
if (nums.length == k) {
return nums;
}
Map<Integer, Integer> countMap = new HashMap<>();

for (int num : nums) {
countMap.put(num, countMap.getOrDefault(num, 0) + 1);
}

Queue<Integer> heap = new PriorityQueue<>((a, b) -> countMap.get(a) - countMap.get(b));

for (int n : countMap.keySet()) {
heap.add(n);
if (heap.size() > k) {
heap.poll();
}
}

int[] ans = new int[k];

for (int i = 0; i < k; i++) {
ans[i] = heap.poll();
}

return ans;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package KeyPatterns.Prefix.Examples;

/**
* Basic Prefix Sum
*
* @apiNote
* - Problem: Given an array, find the sum of elements from index `l`
* to `r`.
*/
public class BasicPrefixSum {
public static void main(String[] args) {
System.out.println("\nBasic Prefix Sum ===> ");

int[] nums = { 2, 4, 5, 1, 6 };
int[] prefix = computePrefixSum(nums);
System.out.println(rangeSum(prefix, 1, 3)); // Output: 10 (4+5+1)
}

private static int[] computePrefixSum(int[] nums) {
int n = nums.length;
int[] prefix = new int[n];
prefix[0] = nums[0];

for (int i = 1; i < n; i++) {
prefix[i] = prefix[i - 1] + nums[i];
}

return prefix;
}

private static int rangeSum(int[] prefix, int l, int r) {
if (l == 0) {
return prefix[r];
}
return prefix[r] - prefix[l - 1];
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package KeyPatterns.Prefix.Examples;

/**
* Count of Even Numbers in a Range
* - Problem : Find the count of even numbers in a subarray [l, r]
*/
public class CountEvenNumbers {
public static void main(String[] args) {
int[] nums = { 2, 4, 5, 1, 6, 3 };
int[] prefixEven = computeEvenPrefix(nums);
System.out.println(countEvens(prefixEven, 1, 4));
}

private static int countEvens(int[] prefixEven, int l, int r) {
if (l == 0) {
return prefixEven[r];
}
return prefixEven[r] - prefixEven[l - 1];
}

private static int[] computeEvenPrefix(int[] nums) {
int n = nums.length;
int[] prefixEven = new int[n];
prefixEven[0] = (nums[0] % 2 == 0) ? 1 : 0;

for (int i = 1; i < n; i++) {
prefixEven[i] = prefixEven[i - 1] + (nums[i] % 2 == 0 ? 1 : 0);
}

return prefixEven;
}
}
28 changes: 28 additions & 0 deletions data_structures/src/KeyPatterns/Prefix/Examples/PrefixXOR.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package KeyPatterns.Prefix.Examples;

public class PrefixXOR {
public static void main(String[] args) {
int[] nums = { 3, 8, 2, 6, 4 };
int[] prefixXor = computePrefixXor(nums);
System.out.println(rangeXor(prefixXor, 1, 4));
}

private static int[] computePrefixXor(int[] nums) {
int n = nums.length;
int[] prefixXOR = new int[n];
prefixXOR[0] = nums[0];

for (int i = 1; i < n; i++) {
prefixXOR[i] = prefixXOR[i - 1] ^ nums[i];
}

return prefixXOR;
}

private static int rangeXor(int[] prefixXor, int l, int r) {
if (l == 0) {
return prefixXor[r];
}
return prefixXor[r] ^ prefixXor[l - 1];
}
}
23 changes: 23 additions & 0 deletions data_structures/src/KeyPatterns/Prefix/Examples/RunningSum.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package KeyPatterns.Prefix.Examples;

/**
* Running Sum (Simple Prefix Sum)
* - Problem: Convert an array into its running sum (prefix sum).
* - Approach: Directly modify an array to store cumulative sum.
*/
public class RunningSum {
public static void main(String[] args) {
int[] nums = { 1, 2, 3, 4 };
int[] result = runningSum(nums);
for (int r : result) {
System.out.println("result ==> " + r);
}
}

private static int[] runningSum(int[] nums) {
for (int i = 1; i < nums.length; i++) {
nums[i] += nums[i - 1];
}
return nums;
}
}
1 change: 1 addition & 0 deletions data_structures/src/KeyPatterns/Prefix/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# Prefix Technique

0 comments on commit b0cd4eb

Please sign in to comment.