TikTok OA Interview Question: Card Packets

15 Views
No Comments

Given an array cardTypes where cardTypes[i] is the number of cards of type i, determine the minimum number of additional cards needed so that the cards can be divided into at least 2 matching packets.

Each packet must contain the same number of cards of each type. You may add cards of any type. Return the minimum total number of additional cards required.

Example

cardTypes = [3, 8, 7, 6, 4]

For 2 packets, add [1, 0, 1, 0, 0] cards to get [4, 8, 8, 6, 4].
This requires 2 additional cards.

For 3 packets, add [0, 1, 2, 0, 2] cards to get [3, 9, 9, 6, 6].
This requires 5 additional cards.

The minimum is 2.

Function Description

Complete the function cardPackets in the editor below.

cardPackets has the following parameter(s):

  • int cardTypes[n]: the quantity available of each card type

Returns

  • int: the minimum number of additional cards to add

Constraints

  • 1 <= n <= 10^5
  • 1 <= cardTypes[i] <= 500

The task is to add as few cards as possible so the counts of every card type can be evenly split into at least two identical packets. The key idea is to try possible packet counts k starting from 2, then for each card type compute how many cards are needed to make its count a multiple of k using (k – count % k) % k. Summing these values gives the cost for that k, and the minimum over all valid k is the answer. With the given limits, a simple enumeration approach is sufficient and matches the sample result of 2 for [3, 8, 7, 6, 4].

END
 0