Taro Logo

Number of Divisible Triplet Sums

#3 Most AskedMedium
0 views
Topics:
ArraysTwo Pointers

Given an integer array nums and an integer d, find the number of index triplets (i, j, k) such that 0 <= i < j < k < nums.length, and the sum nums[i] + nums[j] + nums[k] is divisible by d.

Example 1:

Input: nums = [3,3,6,4,7,5], d = 3
Output: 4
Explanation: The following triplets have a sum divisible by 3:
(3, 3, 6): 3 + 3 + 6 = 12 is divisible by 3
(3, 6, 4): 3 + 6 + 4 = 13. It's wrong.
(3, 6, 5): 3 + 6 + 5 = 14. It's wrong.
(3, 3, 6): 3 + 3 + 6 = 12 is divisible by 3. It's duplicated.
(3, 3, 6): 3 + 3 + 6 = 12 is divisible by 3. It's duplicated.
(3, 6, 4): 3 + 6 + 4 = 13. It's wrong.
(3, 4, 5): 3 + 4 + 5 = 12 is divisible by 3
(3, 7, 5): 3 + 7 + 5 = 15 is divisible by 3
(6, 4, 5): 6 + 4 + 5 = 15 is divisible by 3

Example 2:

Input: nums = [4,2,1,5,3], d = 2
Output: 4
Explanation: The following triplets have a sum divisible by 2:
(4, 2, 1): 4 + 2 + 1 = 7 is not divisible by 2.
(4, 2, 5): 4 + 2 + 5 = 11 is not divisible by 2.
(4, 2, 3): 4 + 2 + 3 = 9 is not divisible by 2.
(4, 1, 5): 4 + 1 + 5 = 10 is divisible by 2.
(4, 1, 3): 4 + 1 + 3 = 8 is divisible by 2.
(4, 5, 3): 4 + 5 + 3 = 12 is divisible by 2.
(2, 1, 5): 2 + 1 + 5 = 8 is divisible by 2.
(2, 1, 3): 2 + 1 + 3 = 6 is divisible by 2.
(2, 5, 3): 2 + 5 + 3 = 10 is divisible by 2.
(1, 5, 3): 1 + 5 + 3 = 9 is not divisible by 2.

Constraints:

  • 3 <= nums.length <= 1000
  • 1 <= nums[i] <= 1000
  • 1 <= d <= 100

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the expected range of the array length and the values inside `nums`, and can we expect negative integers or zeros?
  2. Does "unique triplets of indices (i, j, k)" mean we care about the positions rather than the values, so that if `nums[i] + nums[j] + nums[k]` uses the same values at different index combinations, they are counted separately?
  3. Can the input array contain duplicate values, and if so, how should they impact the uniqueness of the index triplets `(i, j, k)`?
  4. What should be returned if fewer than 3 elements are present in the input array?
  5. What is the data type and range for the divisor `d`, and is it guaranteed to be a positive integer greater than zero?

Brute Force Solution

Approach

Imagine you have a collection of items, and you want to find every possible group of three that meets a specific target rule. The brute force strategy involves checking every single possible combination of three items without missing a single one.

Here's how the algorithm would work step-by-step:

  1. Begin by looking at the very first three items in your collection.
  2. Add up the values of these three items together.
  3. Check to see if this combined total can be divided evenly by the special number you were given.
  4. If the total divides evenly, keep a mental note that you found a successful group.
  5. Next, shift your attention slightly to check the next possible combination of three items.
  6. Repeat this process of picking three items, adding them up, and testing the division for every conceivable trio in your collection.
  7. Once you have checked every single combination possible, count up all the successful groups you found and report that final total.

Code Implementation

def count_divisible_triplets(number_list, divisor):
    successful_groups_count = 0
    
    # Iterate through every possible unique combination of three elements in the collection
    for first_index in range(len(number_list)):
        for second_index in range(first_index + 1, len(number_list)):
            for third_index in range(second_index + 1, len(number_list)):
                
                # Sum the values of the current trio to evaluate against the division rule
                trio_sum = number_list[first_index] + number_list[second_index] + number_list[third_index]
                
                # Verify if the combined total is evenly divisible by the specified divisor
                if trio_sum % divisor == 0:
                    successful_groups_count += 1
                    
    return successful_groups_count

Big(O) Analysis

Time Complexity
–
Space Complexity
O(1) – The brute force strategy described only utilizes a few primitive integer variables to track the outer, middle, and inner loops along with the final running count of successful groups. No auxiliary data structures like hash maps or temporary lists are created to store intermediate combinations. The space required remains constant regardless of the input size N, resulting in an auxiliary space complexity of O(1).

Optimal Solution

Approach

Instead of checking every single possible combination of three items, the optimal approach works systematically from left to right. By keeping a running tally of previously seen items, it figures out how many valid groupings can be formed efficiently.

Here's how the algorithm would work step-by-step:

  1. Imagine walking down a row of items from left to right, focusing on one item at a time.
  2. As you look at a specific item, treat all the items you have already passed as a collection of historical choices.
  3. Ask yourself how many pairs from your historical choices, when combined with your current item, add up to a total that divides evenly by your target number.
  4. Keep a mental tally of these successful combinations without having to recount them from scratch.
  5. Once you finish evaluating the current item, add it to your collection of historical choices so future items can use it.
  6. Continue this process until you reach the end of the row, letting your running tally give you the final count of valid groupings.

Code Implementation

from collections import defaultdict

def divisible_triplet_sum(array_of_numbers, divisor):
    total_valid_triplets = 0
    history_frequency_map = defaultdict(int)

    for middle_index in range(len(array_of_numbers)):
        current_item = array_of_numbers[middle_index]

        for left_index in range(middle_index):
            historical_item = array_of_numbers[left_index]
            remainder_target = (divisor - ((historical_item + current_item) % divisor)) % divisor
            total_valid_triplets += history_frequency_map[remainder_target]

        # Past items are recorded so future elements can form valid pairs with them.
        history_frequency_map[current_item % divisor] += 1

    return total_valid_triplets

Big(O) Analysis

Time Complexity
O(n²) – The algorithm uses a single outer loop of size n to walk through each element, while an inner traversal iterates over all previously seen elements to check potential pairs. For the first element we check 0 historical items, for the second 1, for the third 2, and so on up to n-1. This progressive accumulation leads to approximately n * n/2 operations, which simplifies to O(n²).
Space Complexity
O(N) – The auxiliary space is driven by a hash map used to keep a running tally of previously seen items as we walk down the row from left to right. In the worst-case scenario, this collection of historical choices stores a unique entry for every element up to size N. Therefore, the memory consumed scales linearly with the input size N. Ultimately, the total extra memory simplifies to Big O notation of O(N).

Edge Cases

Array with fewer than three elements
How to Handle:
Return zero immediately since it is impossible to form a triplet of indices where i < j < k.
Negative numbers in the array
How to Handle:
Use modulo arithmetic that correctly handles negative remainders by shifting them into the positive range before looking up counts.
All elements are identical
How to Handle:
Precompute frequency maps or iterate combinations carefully to ensure identical values at different indices are counted correctly without illegal index reuse.
Sum divisible by d using zero values
How to Handle:
Ensure the algorithm correctly counts combinations involving zeros, which act as neutral elements for the modulo sum.
No valid triplets exist
How to Handle:
The counter will naturally remain at zero and return the correct result after checking all valid index combinations.
Large input arrays up to maximum constraints
How to Handle:
Optimize the time complexity from cubic to quadratic using a frequency map of prefix or suffix remainders to avoid time limit exceeded errors.
Integer overflow during sum calculation
How to Handle:
Take the modulo of intermediate sums or use larger integer types to prevent arithmetic overflow when adding large array elements.
Divisor d is equal to one
How to Handle:
Return the total number of possible triplets since any integer sum is trivially divisible by one.
0/3 completed