FastPrepArithmetic Triplets After Queries

Arithmetic Triplets After Queries

TikTok logoTikTok● HardNEW GRADOA
Learn

Problem statement

Start with an empty collection numbers. Process each string in queries in order:

  • "+x" appends one occurrence of integer x. Repeated values are allowed.
  • "-x" removes all occurrences of integer x. Each removal is guaranteed to target a value currently present.

After every query, count the triples (x,y,z) that can be formed from the current occurrences such that x-y = y-z = diff. The collection may be rearranged; original insertion positions do not restrict a triple. Count different choices of occurrences separately. For example, two copies of each of three suitable values contribute 2 × 2 × 2 = 8 triples.

Return an integer array containing the count after each query. For this practice version, assume diff is positive, so the three values in a valid triple are distinct.

Query syntax

The first character is the operation. Parse the entire remaining substring as the integer value, which can itself be negative. Thus "+-5" appends -5, "--5" removes all copies of -5, and "-5" removes all copies of positive 5. Payloads use ordinary decimal notation without whitespace, a leading plus sign, or leading zeros; zero is written 0.

Function

countTripletsAfterQueries(queries: String[], diff: int) → int[]

Examples

Example 1

queries = ["+4","+5","+6","+4","+3","-4"]diff = 1return = [0,0,1,2,4,0]

The first triple is (6,5,4). Adding a second 4 gives two occurrence choices. Adding 3 also creates two copies of (5,4,3), bringing the total to four. The last query removes both copies of 4, so no triple remains.

Example 2

queries = ["+-2","+-1","+0","+-1","--1","+-1"]diff = 1return = [0,0,1,2,0,1]

The strings append negative values -2 and -1 before adding 0. Two copies of -1 yield two choices for (0,-1,-2). Query "--1" removes both copies; appending one again restores one triple.

Constraints

  • For this practice version, assume 1 <= queries.length <= 4000.
  • Every payload value is in [-10^9,10^9].
  • For this practice version, assume 1 <= diff <= 10^9.
  • Every query follows the stated syntax, and every removal targets a currently present value.
  • Each answer is between 0 and 2^31-1, inclusive.
  • Use 64-bit arithmetic for neighbor values and intermediate products.

More TikTok problems

See TikTok hiring insights
public int[] countTripletsAfterQueries(String[] queries, int diff) {
    // write your code here
}
queries["+4","+5","+6","+4","+3","-4"]
diff1
expected[0,0,1,2,4,0]
Checking account…