Блог пользователя Jayanth25

Автор Jayanth25, история, 4 недели назад, По-английски

A. Counting Orders — From Brute Force to an O(N log N) Solution

Problem: A. Counting Orders

Topics: Sorting, Binary Search, Greedy, Combinatorics

While solving this problem, I went through multiple approaches before arriving at the final observation. Initially, I could solve smaller cases manually, but converting that understanding into an efficient algorithm took some thinking.

In this blog, I’ll explain how I approached the problem, what I tried, where I got stuck, and the observation that finally helped me solve it.

1. Understanding the Problem

We are given two arrays a and b, each containing n integers.

All elements of a are distinct.

We need to find the number of ways to rearrange array a such that:

a[i] > b[i] for every index i.

The answer must be calculated modulo 10^9 + 7.

In simple words, we need to count the number of permutations of a where every element is strictly greater than the corresponding element in b.

2. My Initial Approach: Manual Counting

When I first read the problem, I tried arranging the elements of a manually and counting the valid permutations.

For smaller values of n, I could calculate the answer by checking which elements could be placed at each position.

However, I couldn’t find a systematic way to extend this approach to larger constraints.

So, I started thinking about how to convert this observation into an algorithm.

3. First Observation: Sorting Both Arrays

My first idea was to sort both arrays in ascending order.

After thinking about the condition, I realised something important.

For every element b[i], I need to find how many elements in a are strictly greater than it.

If there are k such elements, then any of those k elements can be placed at that position.

This gave me an idea:

Instead of checking every possible permutation, I could count the number of elements greater than each b[i].

However, directly checking every element of a for every element of b would take O(N²) time.

That would result in TLE for the given constraints.

4. Second Approach: Sorting and Binary Search

To optimise the counting process, I thought about sorting array a and using binary search.

Since a is sorted in ascending order, I can use upper_bound() to find the first element strictly greater than the current b[i].

The number of elements greater than b[i] becomes:

count = a.end() — upper_bound(a.begin(), a.end(), b[i])

This allows me to calculate the count in O(log N).

So far, the approach looked promising.

But there was still something missing.

I was calculating how many elements were greater than each b[i], but I wasn’t considering the elements that had already been assigned to previous positions.

This was the point where I got stuck.

----------------------------------------------------

5. The Missing Observation: Previously Used Elements

I then thought about the order in which I should process the elements of b.

What if I sort b in descending order?

This way, I process the largest element first.

Why does this help?

Consider the following example:

a = [3, 5, 7, 9]

b = [2, 2, 4, 6]

After sorting:

a = [3, 5, 7, 9]

b = [6, 4, 2, 2]

Now, let’s process the elements of b one by one.

Step 1: b[i] = 6

Elements in a strictly greater than 6:

[7, 9]

Available choices = 2.

Step 2: b[i] = 4

Elements in a strictly greater than 4:

[5, 7, 9]

There are 3 possible elements.

But one element has already been used in the previous position.

Therefore:

Available choices = 3 — 1 = 2.

Step 3: b[i] = 2

Elements in a strictly greater than 2:

[3, 5, 7, 9]

There are 4 possible elements.

But two elements have already been used.

Therefore:

Available choices = 4 — 2 = 2.

Step 4: b[i] = 2

Again, there are 4 elements greater than 2.

But three elements have already been used.

Therefore:

Available choices = 4 — 3 = 1.

Final Calculation

The total number of valid permutations is:

ans = 2 × 2 × 2 × 1

ans = 8

And that’s the observation I was missing!

For every position, I need to subtract the number of elements that have already been assigned.

Since we are processing b in descending order, all previously assigned elements are also strictly greater than the current b[i].

Therefore, the number of available choices becomes:

choices = count — i

Here, i is the current zero-based index.

6. Final Approach

Now the complete approach becomes straightforward.

  1. Sort array a in ascending order.
  2. Sort array b in descending order.
  3. Iterate through the sorted array b.
  4. Use upper_bound() on a to count the elements strictly greater than the current b[i].
  5. Subtract i to exclude the elements already assigned.
  6. Multiply the remaining choices into the answer.
  7. Take modulo 10^9 + 7.

If the number of available choices becomes zero or negative, the answer is zero.

7. C++ Implementation

include <bits/stdc++.h>

using namespace std;

define ll long long

const ll MOD = 1e9 + 7; void solve() { int n; cin >> n; vector a(n), b(n); for (auto &x : a) cin >> x; for (auto &x : b) cin >> x; sort(a.begin(), a.end()); sort(b.rbegin(), b.rend()); ll ans = 1; for (int i = 0; i < n; i++) { ll cnt = a.end() — upper_bound(a.begin(), a.end(), b[i]); ll ways = cnt — i; if (ways <= 0) { ans = 0; break; } ans = (ans * ways) % MOD; } cout << ans << '\n'; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int t; cin >> t; while (t--) { solve(); } return 0; }

8. Complexity Analysis

Let N be the size of the arrays.

  • Sorting array a: O(N log N)
  • Sorting array b: O(N log N)
  • Performing binary search for every element: O(N log N)
  • Multiplying the available choices: O(N)

Overall Time Complexity: O(N log N)

Space Complexity: O(N) for storing the two arrays.

This efficiently handles the given constraints.

9. What I Learned From This Problem

The most important lesson I learned while solving this problem was that simply counting the elements satisfying a condition is not always sufficient.

We also need to think about how previous choices affect the number of choices available at the current position.

Initially, I was only thinking about finding the number of elements greater than b[i].

Then I moved to sorting and binary search to optimise the counting process.

But the actual breakthrough came when I realised that I needed to account for the elements already assigned.

Sometimes, the difference between a TLE solution and an optimal solution is not a completely different algorithm. It is just one additional observation.

Keep observing, keep questioning your approach, and never stop thinking about why something works.

Полный текст и комментарии »

  • Проголосовать: нравится
  • -16
  • Проголосовать: не нравится

Автор Jayanth25, история, 4 недели назад, По-английски

Understanding the 3Sum Problem

The 3Sum problem is a classic problem in Data Structures and Algorithms. It helps us understand how sorting and the Two Pointers technique can optimize a brute-force solution.

Let’s understand how to approach this problem step by step.

  1. Problem Statement

Given an integer array nums, find all unique triplets [nums[i], nums[j], nums[k]] such that:

  • i != j
  • i != k
  • j != k
  • nums[i] + nums[j] + nums[k] == 0

The answer should not contain duplicate triplets.

Example

Input:

nums = [-1, 0, 1, 2, -1, -4]

Output:

[[-1, -1, 2], [-1, 0, 1]]

Explanation:

The two unique triplets whose sum is zero are:

  • (-1) + (-1) + 2 = 0
  • (-1) + 0 + 1 = 0
  1. Approach 1: Brute Force

The simplest approach is to generate every possible combination of three elements using three nested loops.

For every combination, check whether its sum is zero.

If it is zero, store the triplet.

To avoid duplicates, we can sort each triplet and use a set.

C++ Code

vector<vector> threeSum(vector& a) { int n = a.size(); set<vector> s; for(int i = 0; i < n; i++) { for(int j = i + 1; j < n; j++) { for(int k = j + 1; k < n; k++) { if(a[i] + a[j] + a[k] == 0) { vector v = {a[i], a[j], a[k]}; sort(v.begin(), v.end()); s.insert(v); } } } } return vector<vector>(s.begin(), s.end()); }

Complexity Analysis

  • Time Complexity: O(N³ log M), where M is the number of unique triplets, due to set insertion and sorting.
  • Space Complexity: O(M) for storing unique triplets.

This approach works, but it becomes too slow when the array size increases.

Can we optimize it?

  1. Approach 2: Sorting + Two Pointers

This is where the Two Pointers technique comes into play.

Intuition

Instead of checking every possible combination, we can sort the array first.

After sorting, we fix one element and use two pointers to find the remaining two elements.

Let:

  • i represent the first element.
  • j represent the second element.
  • k represent the third element.

Initially:

  • j = i + 1
  • k = n — 1

Now calculate:

sum = a[i] + a[j] + a[k]

There are three possibilities:

Case 1: sum == 0

We found a valid triplet.

Store the triplet and move both pointers.

Case 2: sum < 0

The sum is too small.

Since the array is sorted, increase j to get a larger value.

Case 3: sum > 0

The sum is too large.

Decrease k to get a smaller value.

Continue until the two pointers meet.

C++ Code

vector<vector> threeSum(vector& a) { int n = a.size(); vector<vector> ans; sort(a.begin(), a.end()); for(int i = 0; i < n; i++) { if(i > 0 && a[i] == a[i — 1]) continue; int j = i + 1; int k = n — 1; while(j < k) { int sum = a[i] + a[j] + a[k]; if(sum < 0) { j++; } else if(sum > 0) { k--; } else { ans.push_back({a[i], a[j], a[k]}); j++; k--; while(j < k && a[j] == a[j — 1]) j++; while(j < k && a[k] == a[k + 1]) k--; } } } return ans; }

  1. Dry Run

Consider:

a = [-1, 0, 1, 2, -1, -4]

After sorting:

[-4, -1, -1, 0, 1, 2]

First, fix i = 0.

a[i] = -4 j = 1 k = 5

Sum:

-4 + (-1) + 2 = -3

Since the sum is negative, increment j.

Continue checking until the pointers meet. No valid triplet is found with -4.

Now fix i = 1.

a[i] = -1 j = 2 k = 5

Sum:

-1 + (-1) + 2 = 0

We found our first triplet:

[-1, -1, 2]

Move both pointers.

Now:

j = 3 k = 4

Sum:

-1 + 0 + 1 = 0

We found our second triplet:

[-1, 0, 1]

The pointers now meet, so we stop.

Final Answer:

[[-1, -1, 2], [-1, 0, 1]]

  1. Complexity Analysis

Let N be the size of the array.

  • Sorting: O(N log N)
  • Outer loop: O(N)
  • Two-pointer traversal: O(N) for each fixed element.

Therefore:

Time Complexity: O(N²)

Auxiliary Space Complexity: O(1), excluding the sorting implementation and output storage.

  1. Important Things to Remember

  2. Sorting makes the Two Pointers technique possible.

  3. Fix one element and search for the remaining two.
  4. If the sum is smaller than the target, move the left pointer forward.
  5. If the sum is greater than the target, move the right pointer backward.
  6. Always handle duplicates to avoid repeated triplets.

Conclusion

The most important lesson from this problem is that we don’t always need to check every possible combination.

By sorting the array and using the Two Pointers technique, we reduce the time complexity from cubic to quadratic.

This pattern is also useful in several related problems, such as 4Sum, Two Sum II and other pair or triplet sum problems.

Keep practising and keep improving!

Полный текст и комментарии »

  • Проголосовать: нравится
  • -26
  • Проголосовать: не нравится