Langford sequence implementation Haskell or C
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
A Langford sequence arranges pairs of numbers so each value k appears twice with exactly k values between the pair. It is a classic constraint search problem and a good example of practical backtracking. Implementations in C and Haskell use the same mathematical rule but differ in memory model and expression style.
Core Sections
Start With the Feasibility Rule
Before searching, apply the existence condition. A Langford sequence exists only when n mod 4 is 0 or 3. This single check removes impossible inputs and prevents wasted recursion.
For n values that fail this rule, no algorithm can produce a valid arrangement.
Backtracking Design That Scales Better
Use an array of length 2n. For each value k, try placing one copy at index i and the second at i + k + 1. Both positions must be free. Then recurse to k - 1.
Useful implementation decisions:
- place larger values first for stronger pruning
- stop on first solution when only one answer is needed
- continue search for counting mode
This pattern gives a clear recursion tree and simple correctness reasoning.
C Implementation for Speed and Control
C is convenient for this problem because mutable arrays and explicit backtracking are fast and straightforward.
This version returns one solution quickly for small and medium values of n.
Haskell Implementation for Declarative Search
Haskell models the same placement logic in a functional style. The code below returns all solutions for a given n.
Related reading
- Large scale Machine Learning
- Largest 5 in array of 10 numbers without sorting
- Largest and smallest number of internal nodes in red-black tree?
- Largest circle inside a non-convex polygon
- Lazy combinations of c ranges view
- Least Recently Used cache using C
- Largest rectangles in histogram
- Largest sum of upper-left quadrant of matrix that can be formed by reversing rows and columns

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.