Approaches
💡
Intuition
Time O(n²)Space O(1)
The brute force approach checks every possible pair of indices to see if they satisfy the nice pair condition. This is straightforward but inefficient for large arrays.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a counter to zero for counting nice pairs.
- 2Step 2: Loop through each pair of indices (i, j) where i < j.
- 3Step 3: For each pair, calculate rev(nums[i]) and rev(nums[j]). Check if nums[i] + rev(nums[j]) equals nums[j] + rev(nums[i]). If true, increment the counter.
- 4Step 4: Return the counter modulo 10^9 + 7.
solution.py14 lines
1# Full working Python code
2
3def rev(x):
4 return int(str(x)[::-1])
5
6def countNicePairs(nums):
7 MOD = 10**9 + 7
8 count = 0
9 n = len(nums)
10 for i in range(n):
11 for j in range(i + 1, n):
12 if nums[i] + rev(nums[j]) == nums[j] + rev(nums[i]):
13 count += 1
14 return count % MODℹ
Complexity note: This complexity arises because we are checking every pair of indices in a nested loop, leading to n(n-1)/2 comparisons.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.