Arrays & Hashing · Pattern 6 of 26

Right to left: suffix maximums, products and carries

Some answers depend on everything to the right. Walk from the end and carry what you need: the largest value so far, a running product, or a carry digit.

4 variations · 12 problems · 2 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • "Greater than every element to its right"
  • Product or sum of everything except me
  • Adding or multiplying numbers stored as strings or digit arrays
  • The next permutation or next bigger number

The template

Right to Left Traversal
// leaders: elements greater than every element to their right
int[] leaders(int[] a) {
    List<Integer> out = new ArrayList<>();
    int best = Integer.MIN_VALUE;                // largest value seen to the right
    for (int i = a.length - 1; i >= 0; i--) {
        if (a[i] > best) { out.add(a[i]); best = a[i]; }
    }
    Collections.reverse(out);                    // back to left-to-right order
    return out.stream().mapToInt(Integer::intValue).toArray();
}

The variations

  1. 1Carry the best value from the right

    One pass from the end with the maximum so far answers "is anything to my right bigger?" for every index.

  2. 2Prefix and suffix products

    Answer[i] = product of everything left of i × product of everything right of i. Fill the left products forward, then multiply in the right products backward.

  3. 3Next permutation

    From the right, find the first i with a[i] < a[i + 1]. Swap a[i] with the smallest bigger value to its right, then reverse the suffix.

  4. 4Digit by digit with a carry

    Add or multiply from the last digit, keeping a carry. For Roman numerals, subtract when a smaller value comes before a bigger one.

    Worked example Add Strings Easy Read the solution

Mistakes to avoid

  • Collecting answers right to left and forgetting to reverse them.
  • Losing the final carry when adding digit strings ("99" + "1" = "100").
  • Dividing for "product except self": it breaks on zeros. Use prefix and suffix products.
Next: In-place transformations →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.