From 11b38ae2a2060c9958e96c0ca5b22196e9aa106b Mon Sep 17 00:00:00 2001 From: Krishna200608 Date: Thu, 1 Jan 2026 19:34:00 +0530 Subject: [PATCH 1/2] Added solutions for Issue #108: Prefix Sum Medium problems --- .../soln/KrishnaSikheriya/Solution1.cpp | 72 ++++++++++++++++++ .../soln/KrishnaSikheriya/Solution2.cpp | 75 +++++++++++++++++++ 2 files changed, 147 insertions(+) create mode 100644 algos/range_queries/PrefixSum/soln/KrishnaSikheriya/Solution1.cpp create mode 100644 algos/range_queries/PrefixSum/soln/KrishnaSikheriya/Solution2.cpp diff --git a/algos/range_queries/PrefixSum/soln/KrishnaSikheriya/Solution1.cpp b/algos/range_queries/PrefixSum/soln/KrishnaSikheriya/Solution1.cpp new file mode 100644 index 0000000..a09132a --- /dev/null +++ b/algos/range_queries/PrefixSum/soln/KrishnaSikheriya/Solution1.cpp @@ -0,0 +1,72 @@ +/** + * Problem: Range Sum Query + * + * Short Problem Statement: + * Given an array of integers and multiple queries, + * each query asks for the sum of elements in a subarray [L, R]. + * + * Approach (Prefix Sum): + * 1. Build a prefix sum array where: + * prefix[i] = sum of elements from index 1 to i + * 2. For any range [L, R], compute the sum in O(1) time as: + * sum(L, R) = prefix[R] - prefix[L - 1] + * + * Time Complexity: + * - Preprocessing: O(N) + * - Each Query: O(1) + * + * Space Complexity: + * - O(N) for prefix sum array + * + * Example: + * Input: + * 5 + * 1 2 3 4 5 + * 3 + * 1 3 + * 2 5 + * 3 3 + * + * Output: + * 6 + * 14 + * 3 + */ + +#include +#include +using namespace std; + +int main() { + ios::sync_with_stdio(false); + cin.tie(nullptr); + + int n; + cin >> n; + + // Original array (1-based indexing) + vector arr(n + 1); + for (int i = 1; i <= n; i++) { + cin >> arr[i]; + } + + // Prefix sum array + // prefix[i] stores sum of elements from index 1 to i + vector prefix(n + 1, 0); + for (int i = 1; i <= n; i++) { + prefix[i] = prefix[i - 1] + arr[i]; + } + + int q; + cin >> q; + + // Process queries + while (q--) { + int l, r; + cin >> l >> r; + long long rangeSum = prefix[r] - prefix[l - 1]; + cout << rangeSum << '\n'; + } + + return 0; +} diff --git a/algos/range_queries/PrefixSum/soln/KrishnaSikheriya/Solution2.cpp b/algos/range_queries/PrefixSum/soln/KrishnaSikheriya/Solution2.cpp new file mode 100644 index 0000000..9587226 --- /dev/null +++ b/algos/range_queries/PrefixSum/soln/KrishnaSikheriya/Solution2.cpp @@ -0,0 +1,75 @@ +/** + * Problem: Count Subarrays with Given Sum + * + * Short Problem Statement: + * Given an array of integers and a value K, + * count the number of subarrays whose sum is exactly K. + * + * Approach (Prefix Sum + Hash Map): + * - Maintain a running prefix sum. + * - If prefixSum[j] - prefixSum[i] = K, + * then the subarray (i+1 to j) has sum K. + * - We store counts of prefix sums seen so far in a hash map. + * + * Steps: + * 1. Initialize prefixSum = 0 and a map to store frequencies. + * 2. For each element: + * - Add it to prefixSum + * - Check if (prefixSum - K) exists in the map + * - Add its frequency to the answer + * - Update the map with current prefixSum + * + * Time Complexity: + * O(N) + * + * Space Complexity: + * O(N) + * + * Example: + * Input: + * 5 5 + * 1 2 3 2 -1 + * + * Output: + * 2 + */ + +#include +#include +#include +using namespace std; + +int main() { + ios::sync_with_stdio(false); + cin.tie(nullptr); + + int n, k; + cin >> n >> k; + + vector arr(n); + for (int i = 0; i < n; i++) { + cin >> arr[i]; + } + + unordered_map freq; + long long prefixSum = 0; + long long count = 0; + + // Base case: prefix sum 0 appears once + freq[0] = 1; + + for (int i = 0; i < n; i++) { + prefixSum += arr[i]; + + // Check if there exists a prefix sum such that + // prefixSum - previousPrefix = k + if (freq.count(prefixSum - k)) { + count += freq[prefixSum - k]; + } + + freq[prefixSum]++; + } + + cout << count << '\n'; + return 0; +} From c7287a72d3c93495702292abda4aa885e5eff1f1 Mon Sep 17 00:00:00 2001 From: Krishna200608 Date: Thu, 1 Jan 2026 20:10:20 +0530 Subject: [PATCH 2/2] Added Correct Solutions for the PrefixSum Medium Question --- .../soln/Krishna200806/Solution1.cpp | 88 ++++++++++ .../soln/Krishna200608/Solution1.cpp | 109 ++++++++++++ .../soln/Krishna200608/Solution2.cpp | 157 ++++++++++++++++++ .../soln/KrishnaSikheriya/Solution1.cpp | 72 -------- .../soln/KrishnaSikheriya/Solution2.cpp | 75 --------- 5 files changed, 354 insertions(+), 147 deletions(-) create mode 100644 algos/range_queries/DifferenceArray/soln/Krishna200806/Solution1.cpp create mode 100644 algos/range_queries/PrefixSum/soln/Krishna200608/Solution1.cpp create mode 100644 algos/range_queries/PrefixSum/soln/Krishna200608/Solution2.cpp delete mode 100644 algos/range_queries/PrefixSum/soln/KrishnaSikheriya/Solution1.cpp delete mode 100644 algos/range_queries/PrefixSum/soln/KrishnaSikheriya/Solution2.cpp diff --git a/algos/range_queries/DifferenceArray/soln/Krishna200806/Solution1.cpp b/algos/range_queries/DifferenceArray/soln/Krishna200806/Solution1.cpp new file mode 100644 index 0000000..5161c95 --- /dev/null +++ b/algos/range_queries/DifferenceArray/soln/Krishna200806/Solution1.cpp @@ -0,0 +1,88 @@ +/** + * Problem: Range Update Queries (CSES 1651) + * Link: https://cses.fi/problemset/task/1651/ + * Difficulty: Easy (as per repo classification) + * + * Short Problem Statement: + * Given an array of N integers, process Q queries of two types: + * 1. Increase value in range [a, b] by u. + * 2. Find the current value at position k. + * + * Approach (Difference Array + Fenwick Tree): + * While a standard Difference Array allows O(1) updates, calculating a point value + * requires O(N) time (prefix sum), which is too slow for mixed queries (O(NQ)). + * * To solve this efficiently: + * 1. We use the concept of a Difference Array: + * - Update [L, R] by +X is equivalent to: + * diff[L] += X + * diff[R+1] -= X + * 2. We use a Fenwick Tree (Binary Indexed Tree) to maintain these difference updates. + * - The BIT allows us to perform the updates and calculate prefix sums in O(log N). + * 3. The value at index `k` is: Initial_Array[k] + Prefix_Sum_of_Diff(k). + * + * Time Complexity: O((N + Q) log N) + * Space Complexity: O(N) + */ + +#include +#include + +using namespace std; + +const int MAXN = 200005; +long long bit[MAXN]; +int n, q; + +// Update operation for Fenwick Tree (1-based indexing) +void update(int idx, long long val) { + for (; idx <= n; idx += idx & -idx) { + bit[idx] += val; + } +} + +// Query prefix sum up to idx +long long query(int idx) { + long long sum = 0; + for (; idx > 0; idx -= idx & -idx) { + sum += bit[idx]; + } + return sum; +} + +void solve() { + cin >> n >> q; + + vector initial_arr(n + 1); + for (int i = 1; i <= n; i++) { + cin >> initial_arr[i]; + } + + // Process queries + while (q--) { + int type; + cin >> type; + + if (type == 1) { + // Range Update: 1 a b u + int a, b; + long long u; + cin >> a >> b >> u; + // Apply difference array logic using BIT + update(a, u); + update(b + 1, -u); + } else { + // Point Query: 2 k + int k; + cin >> k; + // Result is initial value + accumulated changes + cout << initial_arr[k] + query(k) << "\n"; + } + } +} + +int main() { + ios_base::sync_with_stdio(false); + cin.tie(NULL); + solve(); + return 0; +} \ No newline at end of file diff --git a/algos/range_queries/PrefixSum/soln/Krishna200608/Solution1.cpp b/algos/range_queries/PrefixSum/soln/Krishna200608/Solution1.cpp new file mode 100644 index 0000000..65831a0 --- /dev/null +++ b/algos/range_queries/PrefixSum/soln/Krishna200608/Solution1.cpp @@ -0,0 +1,109 @@ +/* +==================================================== +Problem: Reverse Sort (Codeforces 1605B) +==================================================== + +------------------------- +Short Problem Statement +------------------------- +You are given a binary string of length n. +In one operation, you may choose any subsequence of indices +and reverse the characters at those positions. +Determine whether the string can be sorted so that all 0s +come before all 1s. If possible, output the indices used +in at most one operation. + +------------------------- +Approach (Prefix Sums + Difference Logic) +------------------------- +1. In a sorted binary string: + - All '0's appear first, then all '1's. +2. Let cnt0 be the total number of '0's in the string. + - Indices [0 ... cnt0-1] must be '0' + - Indices [cnt0 ... n-1] must be '1' +3. Build prefix sums: + - pref0[i] = number of '0's in s[0 ... i-1] + - pref1[i] = number of '1's in s[0 ... i-1] +4. Using cnt0, check each position: + - If s[i] != expected character, mark index (i+1) +5. If no mismatches exist → already sorted. +6. Otherwise, reversing all mismatched indices in ONE + operation always fixes the string. + +------------------------- +Time & Space Complexity +------------------------- +Time Complexity: O(n) per test case +Space Complexity: O(n) + +------------------------- +Example (Optional) +------------------------- +Input: +1 +5 +11001 + +Output: +1 +4 1 2 4 5 + +------------------------- +Clean, Compiling C++ Code +------------------------- +*/ + +#include +using namespace std; + +void solve() { + int n; + cin >> n; + string s; + cin >> s; + + // Prefix sums + vector pref0(n + 1, 0), pref1(n + 1, 0); + for (int i = 0; i < n; i++) { + pref0[i + 1] = pref0[i] + (s[i] == '0'); + pref1[i + 1] = pref1[i] + (s[i] == '1'); + } + + int cnt0 = pref0[n]; // total zeros + + vector indices; + + // Identify mismatched positions + for (int i = 0; i < n; i++) { + char expected = (i < cnt0 ? '0' : '1'); + if (s[i] != expected) { + indices.push_back(i + 1); // 1-based indexing + } + } + + // Already sorted + if (indices.empty()) { + cout << 0 << '\n'; + return; + } + + // One reverse operation is sufficient + cout << 1 << '\n'; + cout << indices.size(); + for (int idx : indices) { + cout << " " << idx; + } + cout << '\n'; +} + +int main() { + ios::sync_with_stdio(false); + cin.tie(nullptr); + + int t; + cin >> t; + while (t--) { + solve(); + } + return 0; +} diff --git a/algos/range_queries/PrefixSum/soln/Krishna200608/Solution2.cpp b/algos/range_queries/PrefixSum/soln/Krishna200608/Solution2.cpp new file mode 100644 index 0000000..41ef9b0 --- /dev/null +++ b/algos/range_queries/PrefixSum/soln/Krishna200608/Solution2.cpp @@ -0,0 +1,157 @@ +/* +==================================================== +Problem: Tracking Segments (Codeforces 1843E) +==================================================== + +------------------------- +Short Problem Statement +------------------------- +You are given: +- An array of length n, initially filled with 0s +- m segments [l, r] +- q update operations, where each operation turns one position into 1 + +After each update, more 1s are added (never removed). + +A segment is called "beautiful" if it contains strictly more 1s than 0s. + +Your task is to find the smallest k (1 ≤ k ≤ q) such that +after applying the first k updates, at least one segment becomes beautiful. +If no such k exists, output -1. + +------------------------- +Approach (Binary Search + Prefix Sums) +------------------------- +Key Observations: +- Updates are monotonic: once a position becomes 1, it stays 1 +- The condition "some segment becomes beautiful" is monotonic + (false → true, but never true → false) + +Thus, we can binary search on k (number of applied updates). + +For a fixed k: +1. Create an array arr[1..n], initially all 0 +2. Apply the first k updates → set arr[queries[i]] = 1 +3. Build prefix sum: + prefix[i] = number of 1s in arr[1..i] +4. For each segment [l, r]: + - ones = prefix[r] - prefix[l-1] + - length = r - l + 1 + - zeros = length - ones + - if ones > zeros → segment is beautiful + +If any segment is beautiful, k is valid. + +------------------------- +Time & Space Complexity +------------------------- +Let: +- n = array size +- m = number of segments +- q = number of updates + +Time Complexity: +- Each check: O(n + m) +- Binary search over q → O((n + m) * log q) + +Space Complexity: +- O(n) for the array and prefix sums + +------------------------- +Example (Optional) +------------------------- +Input: +1 +5 2 +1 3 +2 5 +3 +1 2 3 + +Output: +2 + +Explanation: +After first 2 updates, segment [1,3] has more 1s than 0s. + +------------------------- +Clean, Compiling C++ Code +------------------------- +*/ + +#include +using namespace std; + +bool check(int k, int n, + const vector>& segments, + const vector& queries) { + + vector arr(n + 1, 0); + + // Apply first k updates + for (int i = 0; i < k; i++) { + arr[queries[i]] = 1; + } + + // Build prefix sum + vector prefix(n + 1, 0); + for (int i = 1; i <= n; i++) { + prefix[i] = prefix[i - 1] + arr[i]; + } + + // Check all segments + for (auto [l, r] : segments) { + int ones = prefix[r] - prefix[l - 1]; + int len = r - l + 1; + int zeros = len - ones; + if (ones > zeros) { + return true; + } + } + + return false; +} + +void solve() { + int n, m; + cin >> n >> m; + + vector> segments(m); + for (int i = 0; i < m; i++) { + cin >> segments[i].first >> segments[i].second; + } + + int q; + cin >> q; + vector queries(q); + for (int i = 0; i < q; i++) { + cin >> queries[i]; + } + + int low = 1, high = q, ans = -1; + + // Binary search for earliest valid k + while (low <= high) { + int mid = low + (high - low) / 2; + if (check(mid, n, segments, queries)) { + ans = mid; + high = mid - 1; + } else { + low = mid + 1; + } + } + + cout << ans << '\n'; +} + +int main() { + ios::sync_with_stdio(false); + cin.tie(nullptr); + + int t; + cin >> t; + while (t--) { + solve(); + } + return 0; +} diff --git a/algos/range_queries/PrefixSum/soln/KrishnaSikheriya/Solution1.cpp b/algos/range_queries/PrefixSum/soln/KrishnaSikheriya/Solution1.cpp deleted file mode 100644 index a09132a..0000000 --- a/algos/range_queries/PrefixSum/soln/KrishnaSikheriya/Solution1.cpp +++ /dev/null @@ -1,72 +0,0 @@ -/** - * Problem: Range Sum Query - * - * Short Problem Statement: - * Given an array of integers and multiple queries, - * each query asks for the sum of elements in a subarray [L, R]. - * - * Approach (Prefix Sum): - * 1. Build a prefix sum array where: - * prefix[i] = sum of elements from index 1 to i - * 2. For any range [L, R], compute the sum in O(1) time as: - * sum(L, R) = prefix[R] - prefix[L - 1] - * - * Time Complexity: - * - Preprocessing: O(N) - * - Each Query: O(1) - * - * Space Complexity: - * - O(N) for prefix sum array - * - * Example: - * Input: - * 5 - * 1 2 3 4 5 - * 3 - * 1 3 - * 2 5 - * 3 3 - * - * Output: - * 6 - * 14 - * 3 - */ - -#include -#include -using namespace std; - -int main() { - ios::sync_with_stdio(false); - cin.tie(nullptr); - - int n; - cin >> n; - - // Original array (1-based indexing) - vector arr(n + 1); - for (int i = 1; i <= n; i++) { - cin >> arr[i]; - } - - // Prefix sum array - // prefix[i] stores sum of elements from index 1 to i - vector prefix(n + 1, 0); - for (int i = 1; i <= n; i++) { - prefix[i] = prefix[i - 1] + arr[i]; - } - - int q; - cin >> q; - - // Process queries - while (q--) { - int l, r; - cin >> l >> r; - long long rangeSum = prefix[r] - prefix[l - 1]; - cout << rangeSum << '\n'; - } - - return 0; -} diff --git a/algos/range_queries/PrefixSum/soln/KrishnaSikheriya/Solution2.cpp b/algos/range_queries/PrefixSum/soln/KrishnaSikheriya/Solution2.cpp deleted file mode 100644 index 9587226..0000000 --- a/algos/range_queries/PrefixSum/soln/KrishnaSikheriya/Solution2.cpp +++ /dev/null @@ -1,75 +0,0 @@ -/** - * Problem: Count Subarrays with Given Sum - * - * Short Problem Statement: - * Given an array of integers and a value K, - * count the number of subarrays whose sum is exactly K. - * - * Approach (Prefix Sum + Hash Map): - * - Maintain a running prefix sum. - * - If prefixSum[j] - prefixSum[i] = K, - * then the subarray (i+1 to j) has sum K. - * - We store counts of prefix sums seen so far in a hash map. - * - * Steps: - * 1. Initialize prefixSum = 0 and a map to store frequencies. - * 2. For each element: - * - Add it to prefixSum - * - Check if (prefixSum - K) exists in the map - * - Add its frequency to the answer - * - Update the map with current prefixSum - * - * Time Complexity: - * O(N) - * - * Space Complexity: - * O(N) - * - * Example: - * Input: - * 5 5 - * 1 2 3 2 -1 - * - * Output: - * 2 - */ - -#include -#include -#include -using namespace std; - -int main() { - ios::sync_with_stdio(false); - cin.tie(nullptr); - - int n, k; - cin >> n >> k; - - vector arr(n); - for (int i = 0; i < n; i++) { - cin >> arr[i]; - } - - unordered_map freq; - long long prefixSum = 0; - long long count = 0; - - // Base case: prefix sum 0 appears once - freq[0] = 1; - - for (int i = 0; i < n; i++) { - prefixSum += arr[i]; - - // Check if there exists a prefix sum such that - // prefixSum - previousPrefix = k - if (freq.count(prefixSum - k)) { - count += freq[prefixSum - k]; - } - - freq[prefixSum]++; - } - - cout << count << '\n'; - return 0; -}