VOOZH about

URL: https://www.geeksforgeeks.org/dsa/recamans-sequence/

⇱ Recaman's sequence - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Recaman's sequence

Last Updated : 29 Mar, 2025

Given an integer n. Print first n elements of Recaman’s sequence. Recaman's Sequence starts with 0 as the first term. For each next term, calculate previous term - index (if positive and not already in sequence); otherwise, use previous term + index.

Examples:

Input: n = 6
Output: 0, 1, 3, 6, 2, 7
Explanation: According to Recaman's Sequence:

  • 0 (first term)
  • 0 - 1 is negative, so use 0 + 1 = 1
  • 1 - 2 is negative, so use 1 + 2 = 3
  • 3 - 3 is 0, already in sequence, so use 3 + 3 = 6
  • 6 - 4 = 2 (not in sequence, so use it)
  • 2 - 5 is negative, so use 2 + 5 = 7

Input: n = 17
Output: 0, 1, 3, 6, 2, 7, 13, 20, 12, 21, 11, 22, 10, 23, 9, 24, 8

[Brute Force Approach] Using 2 Nested Loops - O(n^2) Time and O(1) Space

The idea is to generate the first n terms of Recaman’s sequence by following its recurrence rule. We start with 0 and iteratively compute the next term as previous term - index if it is positive and not already in sequence; otherwise, we use previous term + index.


Output
0 1 3 6 2 7 

[Expected Approach] Using Hashing - O(n) Time and O(n) Space

The idea is to construct Recaman's sequence efficiently by using hashing to track visited numbers. The approach iterates from 1 to n, computing a candidate value as the previous term minus the index. If this candidate is negative or already exists in seen, we instead add the index. This ensures each number is unique while following the sequence rules.


Output
0 1 3 6 2 7 
Comment
Article Tags:
Article Tags: