A sequence of n numbers (n < 3000) is called Jolly Jumper if the absolute values of the differences between the successive elements take on all possible values from 1 through n-1. The definition implies that any sequence of a single integer is a jolly jumper.
Input: 1 4 2 3 Output: True This sequence 1 4 2 3 is Jolly Jumper because the absolute differences are 3, 2, and 1. Input: 1 4 2 -1 6 Output: False The absolute differences are 3, 2, 3, 7. This does not contain all the values from 1 through n-1. So, this sequence is not Jolly. Input: 11 7 4 2 1 6 Output: True
The idea is to maintain a boolean array to store set of absolute difference of successive elements.
a) If absolute difference between two elements is more than n-1 or 0, return false.
b) If an absolute difference repeated, then all absolute differences from 1 to n-1 can’t be present (Pigeon Hole Principle), return false.
Below is the implementation based on above idea.
Time Complexity: O(n)
This article is contributed by Rahul Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Minimum operations required to transform a sequence of numbers to a sequence where a[i]=a[i+2]
- k-th missing element in increasing sequence which is not present in a given sequence
- Longest sub-sequence with maximum GCD
- Longest sub-sequence with minimum LCM
- Longest sub-sequence with a given OR value : O(N) Approach
- Create a sequence whose XOR of elements is y
- Maximum sum Bi-tonic Sub-sequence
- Largest Derangement of a Sequence
- Check if any valid sequence is divisible by M
- Longest sub-sequence that satisfies the given conditions
- Check if the given Prufer sequence is valid or not
- Find the subsequence with given sum in a superincreasing sequence
- Count permutation such that sequence is non decreasing
- Form minimum number from given sequence
- Delete consecutive same words in a sequence