Given a number N. The task is to find the first N terms of the Golomb Sequence. Golomb sequence is a non-decreasing integer sequence where the n-th term is equal to the number of times n appears in the sequence.
Input: N = 11
Output: 1 2 2 3 3 4 4 4 5 5 5
The first term is 1. 1 appears only once.
The second term is 2. 2 appears two times.
The third term is 2. 3 appears two times.
The fourth term is 3. 4 appears three times.
the fifth term is 3. 5 appears three times.
Input: N = 6
Output: 1 2 2 3 3 4
- Initialise the array arr with  as the Golomb sequence starts with 1.
- Store the value of last index in map M.
- For Golomb sequence till N:
- Intialise cnt = 0 and map the .
- If cnt is not equals to 0 then, then current element in Golomb sequence is the previous element in the sequence and decrease the cnt.
- Else the current element in Golomb sequence is equals to 1 + previous element in the sequence and cnt is updated as the value of map at current element in Golomb sequence and decrease the cnt.
- Map the current index with the current value at Golomb Sequence.
- Print all the element of Golomb Sequence stored in array arr.
Below is the implementation of the above approach:
1 2 2 3 3 4 4 4 5 5 5
Time Complexity: O(N)
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.