Help Ninja to Cross River
Ninja is standing on the edge of a river and wants to cross the river. There is a wooden bridge over the river but some units of the bridge are damaged. Ninja can not step over a damaged unit of the bridge. All the safe units of the bridge are in an array/list ‘SAFE’ which is sorted in increasing order.
Ninja is currently standing on the first safe unit of the bridge and has to reach the last safe unit of the bridge by jumping.
There are some restrictions on the size of jump Ninja can make:
1. The first jump will always be of 1 unit.
2. If Ninja's previous jump was ‘X’ units, his current jump must be either ‘X’ - 1, ‘X’, or ‘X’ + 1 units.
As Ninja is warming up before crossing the bridge, he asks you for help. You need to find out whether Ninja can cross the river or not and return TRUE if Ninja can cross the river else return FALSE.
For example :
If ‘SAFE’ = [1, 2, 4, 7] then it can shown in below image where :
Red cell means that the unit is damaged.
Green cell means that the unit is safe.
We can see Ninja can reach the last unit by making jumps of size 1 , 2 and 3.
Input Format:
The first line of input contains an integer ‘T’ denoting the number of test cases. Then each test case follows.
The first line of each test case contains a single integer ‘N’ denoting the size of ‘SAFE’ or we can say the number of safe units.
The second line contains ‘N’ space-separated distinct integers denoting the elements of ‘SAFE’.
Output format:
For each test case return, true if Ninja can cross the river else return false.
Note :
You don’t have to print anything, it has already been taken care of. Just implement the given function.
Constraints
1 <= T <=10
2 <= N <= 10^3
0 <= SAFE[i] <= 10^5
Time limit: 1 sec
CodingNinjas
author
2y
Recursion
Complete Algorithm:
- First of all, we will make a HashMap say ‘MY_MAP’ to store safe units where the key will be ‘SAFE[i]’ and the value will be ‘i’.
- We will make a helper recursive function nam...read more
CodingNinjas
author
2y
Recursion + Memoization
Our last approach was very simple and easy, but its time complexity was of exponential order. We can improve our solution by taking care of the overlapping subproblems. Thus, we...read more
CodingNinjas
author
2y
Bottom-Up DP
Our earlier approach (recursion with memoization) surely avoided some subproblems but we can still improve time complexity using a bottom-up approach. So we will make a 2-D array say DP wh...read more
Add answer anonymously...
Top ThoughtWorks Software Developer interview questions & answers
Popular interview questions of Software Developer
Top HR questions asked in ThoughtWorks Software Developer
>
ThoughtWorks Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app