DEV Community

mzakzook
mzakzook

Posted on

1

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.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay