DEV Community

mzakzook
mzakzook

Posted on

Count Number of Teams

I came across another LeetCode problem that I felt was worth exploring here. It's called 'Count Number of Teams'.

The problem tells us that there will be an input array of unique integers; each integer representing an individual's rating. We must return the number of 'teams' that can be formed from the input array while satisfying the following criteria:

  • Each team consists of three members
  • A team must be represented in ascending order consistent with each member's index in the input array (indexOfA < indexOfB < indexOfC)
  • A team's ratings must be ascending or descending while adhering to our 2nd bullet point (ratingA < ratingB < ratingC OR ratingA > ratingB > ratingC)

For example:

If given an input array of [2,5,3,4,1], our return would be 3. This is because we can construct three valid teams from this array. The first is (2, 3, 4) because 2 < 3 & 3 < 4 AND indexOf(2) < indexOf(3) & indexOf(3) < indexOf(4). Our second team is (5, 3, 1) because 5 > 3 & 3 > 1 AND indexOf(5) < indexOf(3) & indexOf(3) < indexOf(1). The last valid team is (5, 4, 1) because 5 > 4 & 4 > 1 AND indexOf(5) < indexOf(4) & indexOf(4) < indexOf(1).

I went about solving this problem with brute force. I constructed three for loops to check every possible combination of a team from the input array. If the team satisfies the ascending/descending requirement then I increment my result variable.

When we exit the outside for loop we should have counted every valid team. The last step is to return the counter, which I named result.

var numTeams = function(rating) {
    let result = 0;
    for (let i = 0; i < rating.length; i++) {
        for (let y = i + 1; y < rating.length; y++) {
            for (let z = y + 1; z < rating.length; z++) {
                if ((rating[i] < rating[y] && rating[y] < rating[z]) || (rating[i] > rating[y] && rating[y] > rating[z])) result += 1;
            }
        }
    }
    return result;
};

I find these types of problems to be very helpful in forcing me to consider how to dissect a problem and I look forward to working through more.

Top comments (0)