Problem 1395

Abstract / Summary

Count the number of triplets in an array where one element is smaller than the other two.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1395.py

class Solution:
    def numTeams(self, rating: List[int]) -> int:
        result = 0

        seen = set()            # i of one soldier
        up   = defaultdict(int) # j for two soldiers where r[i] < r[j]
        down = defaultdict(int) # j for two soldiers where r[i] > r[j]

        for r in rating:
            # triples
            for u in up:
                if r > u:
                    result += up[u]
            for d in down:
                if r < d:
                    result += down[d]

            # pairs
            for s in seen:
                if s < r:
                    up[r]   += 1
                else:
                    down[r] += 1

            seen.add(r)

        return result
27 lines | 742 bytes | submitted November 9, 2023 | GitHub   25% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 70% (300k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Binary Indexed Tree
  • Dynamic Programming
  • Segment Tree
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The function numTeams computes the number of valid three-soldier teams that can be formed from a list of soldier ratings. A team is valid when the three ratings are either strictly increasing or strictly decreasing in the order they appear in the original list. The algorithm processes the ratings in a single left-to-right pass while maintaining auxiliary structures that capture pairwise relationships seen so far. By incrementally updating counts for potential triples, the solution avoids a cubic enumeration of all index triples.

Initialization

The method begins by creating three containers that will be updated as the iteration proceeds.

result = 0

seen = set()            # stores ratings of soldiers already processed
up   = defaultdict(int) # maps a rating to the number of increasing pairs ending with that rating
down = defaultdict(int) # maps a rating to the number of decreasing pairs ending with that rating

result holds the final count. seen records every rating encountered, enabling quick determination of whether a new rating forms an increasing or decreasing pair with any earlier rating. The dictionaries up and down accumulate counts of two-soldier sequences that can later be extended to a three-soldier team.

Processing each rating

The core of the algorithm is a loop that examines each rating r in the input order.

for r in rating:
    # triples
    ...
    # pairs
    ...
    seen.add(r)

Inside the loop the code first attempts to close existing pairs into triples, then creates new pairs that involve the current rating, and finally records the rating as seen.

Extending pairs to triples

Two inner loops iterate over the keys of up and down. For each key, the algorithm checks whether the current rating can extend the stored pair into a valid triple.

for u in up:
    if r > u:
        result += up[u]
for d in down:
    if r < d:
        result += down[d]

If r is larger than a key u from up, the pair represented by up[u] (which is an increasing pair ending with u) can be extended to an increasing triple, and the count is added to result. Symmetrically, if r is smaller than a key d from down, the decreasing pair ending with d can be extended to a decreasing triple.

Forming new pairs

After attempting to close triples, the algorithm creates new two-soldier sequences that end with the current rating. It does this by comparing r with every rating already stored in seen.

for s in seen:
    if s < r:
        up[r]   += 1
    else:
        down[r] += 1

When a previously seen rating s is smaller than r, an increasing pair (s, r) is recorded by incrementing up[r]. Otherwise, a decreasing pair (s, r) is recorded by incrementing down[r]. This step ensures that future ratings can later extend these pairs into triples.

Edge-case handling

The algorithm gracefully handles several special input configurations:

  • Empty input - The outer loop never executes, leaving result at its initial value of zero, which correctly represents that no teams can be formed.
  • Single element - With only one rating, the inner loops have no prior data to process, and result remains zero, reflecting the impossibility of forming a three-member team.
  • All equal ratings - Because the comparisons use strict inequality (< and >), equal values never contribute to up or down. Consequently, no pairs or triples are counted, and the function returns zero, matching the problem’s requirement for strictly monotonic sequences.
  • Strictly increasing or decreasing sequences - As each new rating is either larger or smaller than all previously seen values, the inner loops efficiently accumulate the correct number of pairs and subsequently triples, yielding the combinatorial count of valid teams without redundant work.

Performance optimizations

Several design choices contribute to the efficiency of the solution:

  • Incremental counting - By storing the number of pairs that end with each rating, the algorithm avoids recomputing pair counts for every new element. This reduces the work needed to extend pairs into triples to a simple dictionary lookup and addition.
  • Use of defaultdict(int) - The dictionaries automatically initialize missing keys to zero, eliminating explicit existence checks and allowing concise increment operations.
  • Set for seen - The seen container provides O(1) membership tests and enables iteration over only distinct previously encountered ratings, preventing duplicate work when the same rating appears multiple times.
  • Key-based iteration - The loops that extend pairs iterate over the keys of up and down rather than over all possible rating values. This keeps the inner work proportional to the number of distinct ratings encountered so far, which is typically far smaller than the total number of soldiers.
  • Single pass - All necessary information is gathered and utilized during one left-to-right traversal, eliminating the need for a second pass or nested loops that would increase the overall runtime.

Through these techniques the function achieves a practical runtime for typical input sizes while maintaining clear and maintainable logic.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a group of soldiers standing in a long line, and each soldier has a different power level shown by a number. The goal is to pick three soldiers who are standing in a special order.

To do this, the computer walks down the line of soldiers one by one. As it looks at each soldier, it checks if it can make a team of three with the friends it has already met.

The computer keeps two lists. One list remembers soldiers who are smaller than the ones already seen, and the other list remembers soldiers who are bigger. When the computer looks at a new person, it checks the lists to see if the new soldier can make a perfect team of three where everyone is either getting stronger or getting weaker as they stand in line.

If the new soldier fits, the computer adds that team to a final count. Then it adds the new soldier to the lists so it can help form teams later on. By the time it finishes walking through the whole line, it knows how many of these teams exist.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 5.81 | σ = 2.06

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python JS Java Go TS
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
everthis JS
fartem Ruby
fsq C++
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
trung-hn Python
varunu28 Java
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, JavaScript, Python, TypeScript
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fartem Ruby
fsq C++
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
trung-hn Python
varunu28 Java
YuriSpiridonov Python
28 links | 16 authors | 8 languages

Videos

8 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

11 solutions   November 9, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality