Problem 1718

Abstract / Summary

Build the largest sequence by choosing the highest unused number that still allows a complete valid sequence.

Note

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

Python 1718.py

class Solution:
    def constructDistancedSequence(self, n: int) -> List[int]:
        size   = 2 * n - 1
        result = [ None ] * size

        def deeper(pos):
            # done
            if pos == size:
                return True

            # slot occupied, go deeper
            if result[pos] is not None:
                return deeper(pos + 1)

            # larger digits first (9,8,7,...,2)
            for digit in reversed(range(2, n + 1)):
                if digit in result:
                    continue

                # secondary position needs to be empty, too
                other = pos + digit
                if other >= size or result[other] is not None:
                    continue

                # fill in and go deeper
                result[pos] = result[other] = digit
                if deeper(pos + 1):
                    return True

                # failed, reset
                result[pos] = result[other] = None

            # no digit fits, try 1 (only once)
            if 1 not in result:
                result[pos] = 1
                if deeper(pos + 1):
                    return True
                result[pos] = None
            return False

        deeper(0)
        return result
42 lines | 1282 bytes | submitted July 23, 2024 | 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 73% (100k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Backtracking
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 provided implementation builds a distance-constrained sequence for a given integer n. The sequence length is fixed at 2 * n - 1, and each integer from 2 to n must appear exactly twice, with the two occurrences separated by exactly that integer’s value. The integer 1, if used, appears only once. The algorithm employs depth-first backtracking to place numbers in the array while respecting the distance rule.

Core Algorithm

At its heart the solution is a recursive depth-first search (deeper) that attempts to fill the result array from left to right. When the current index reaches the end of the array, the recursion reports success. If a position is already occupied, the recursion simply advances to the next index. Otherwise the routine tries to place the largest still-unused digit that can legally occupy the current slot and its partner slot, recursing after each tentative placement. If none of the larger digits fit, the algorithm makes a single attempt to place the digit 1.

def deeper(pos):
    if pos == size:
        return True
    if result[pos] is not None:
        return deeper(pos + 1)
    # try larger digits first
    for digit in reversed(range(2, n + 1)):
        ...
    # try 1 once
    if 1 not in result:
        ...
    return False

The outer function initializes the working structures and launches the recursion:

size   = 2 * n - 1
result = [ None ] * size
deeper(0)
return result

Detailed Steps

The first step creates the target array filled with None placeholders, establishing the exact length required for a valid sequence.

size   = 2 * n - 1
result = [ None ] * size

The recursive helper receives a position index pos. If pos equals size, the entire array has been successfully populated, and the function returns True to unwind the recursion.

if pos == size:
    return True

When the current slot already contains a value, the algorithm skips it, moving forward without altering the state.

if result[pos] is not None:
    return deeper(pos + 1)

The main placement loop iterates over candidate digits in descending order, starting from n down to 2. This ordering encourages early placement of larger numbers, which have stricter distance constraints, thereby reducing the search space.

for digit in reversed(range(2, n + 1)):
    if digit in result:
        continue
    other = pos + digit
    if other >= size or result[other] is not None:
        continue
    result[pos] = result[other] = digit
    if deeper(pos + 1):
        return True
    result[pos] = result[other] = None

Inside the loop, the algorithm first checks whether the digit has already been placed elsewhere (digit in result). If it has, the digit is skipped. It then computes the partner index other as pos + digit. The partner index must lie within the array bounds and be empty; otherwise the digit cannot be placed at the current position. When both slots are free, the digit is written to both positions, and the recursion proceeds. If deeper recursion fails, the placement is undone (backtracked) by resetting both slots to None.

After exhausting all larger digits, the routine makes a single attempt to place the digit 1, which only occupies a single slot. The check if 1 not in result guarantees that 1 is used at most once.

if 1 not in result:
    result[pos] = 1
    if deeper(pos + 1):
        return True
    result[pos] = None

If no placement leads to a complete solution, the function returns False, causing the caller to backtrack further up the recursion tree.

Edge Cases Handled

The algorithm gracefully deals with the smallest possible input, n = 1. In this case size becomes 1, the result array contains a single None, and the only viable digit is 1. The loop over larger digits is skipped, and the special handling for 1 places it at position 0, satisfying the constraints.

When a candidate digit’s partner index would fall outside the array (other >= size), the code discards that digit for the current position, preventing index errors. Similarly, if the partner slot is already occupied (result[other] is not None), the digit is rejected, ensuring that no two numbers share a cell.

The check if digit in result prevents reuse of a digit that has already been placed, preserving the requirement that each number from 2 to n appears exactly twice. The condition if 1 not in result enforces the rule that the digit 1 may appear at most once.

By advancing past already-filled slots (if result[pos] is not None), the recursion avoids unnecessary work on positions that are already satisfied by earlier placements.

Performance Optimizations

The search order is deliberately chosen to reduce branching. Trying larger digits first tackles the most restrictive constraints early, which often prunes large portions of the search tree before deeper recursion occurs.

The early-exit pattern (if deeper(pos + 1): return True) stops further exploration as soon as a valid complete sequence is found, preventing the algorithm from continuing to search for alternative solutions once one is discovered.

Backtracking is performed in place by resetting the two affected slots to None after a failed deeper call. This avoids the overhead of copying the entire array for each recursive step, keeping memory usage low and reducing allocation costs.

The use of a single mutable list (result) shared across recursive calls eliminates the need for constructing new data structures at each level, contributing to faster execution.

Finally, the recursion terminates as soon as the index reaches the end of the array, providing a clear base case that prevents unnecessary deeper calls once the solution is complete.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a long train with many empty seats that need to be filled with numbered blocks. The goal is to lay out these blocks so that each number has a specific distance between its two copies. For example, the number two needs to have one empty seat between its two spots, and the number three needs to have two empty seats between its two spots.

To make this happen, the code starts at the very first seat and looks for the biggest available number that fits. It carefully places the number in the current seat and then jumps ahead to find the second spot for that same number. If it finds a spot that is empty, it puts the number there and moves on to the next empty seat to repeat the process. If it gets stuck and cannot place any numbers, it gently takes the blocks back out and tries a different number instead. Think of it like putting together a puzzle where you check every piece to see if it makes the patterns line up perfectly. It keeps exploring these choices until every seat is filled exactly right.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 25 | median = 7 | μ = 7.32 | σ = 1.01

Complexity Analysis

not analyzed yet

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 Java Go
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
haoel C++
JoshCrozier JS
lkwq007 Python
Shamik07 Dart
suxrobGM C#
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
haoel C++
JoshCrozier JavaScript
lkwq007 Python
Shamik07 Dart
suxrobGM C#
wisdompeak C++
24 links | 14 authors | 8 languages

Videos

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

Similar Problems

1 similar problem

Solved On The Same Day

4 solutions   July 23, 2024

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