Count Number of Teams

MediumArrays & Hashinghashing

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Soldiers stand in a line, and rating[i] is the unique rating of the soldier at position i. A team is any three soldiers at positions i < j < k whose ratings are either strictly increasing (rating[i] < rating[j] < rating[k]) or strictly decreasing (rating[i] > rating[j] > rating[k]). A soldier may belong to many teams. Return the number of distinct teams. An O(n^2) solution is fine.

Examples

Input: rating = [2,5,3,4,1]
Output: 3
The teams are (2,3,4), (5,4,1), and (5,3,1).
Input: rating = [2,1,3]
Output: 0
Neither 2,1,3 nor any other ordering of three positions is monotone.
Input: rating = [1,2,3,4]
Output: 4
Every choice of three positions is increasing, and there are C(4,3) = 4 of them.

Constraints

  • 1 <= rating.length <= 1000
  • 1 <= rating[i] <= 10^5
  • All values in rating are distinct

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More hashing problems