Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- https://practice.geeksforgeeks.org/problems/e2d156755ca4e0a9b9abf5680191d4b06e52b1a8/1
- Geek is in a geekland which have a river and some stones in it. Initially geek can step on any stone. Each stone has a number on it representing the value of exact step geek can move. If the number is +ve then geeks will move right by arr[i] and if the number is -ve then geeks move left by arr[i]. Bad Stones are defined as the stones in which if geeks steps, will reach a never ending loop whereas good stones are the stones which are safe from never ending loops. Return the number of good stones in river.
- Example 1:
- Input: [2, 3, -1, 2, -2, 4, 1]
- Output: 3
- Explanation: Index 3, 5 and 6 are safe only. As index 1, 4, 2 forms a cycle and from index 0 you can go to index 2 which is part of cycle.
- Example 2:
- Input: [1, 0, -3, 0, -5, 0]
- Output: 2
- Explanation: Index 2 and 4 are safe only. As index 0, 1, 3, 5 form cycle.
- Expected Time Complexity : O(N), N is the number of stones
- Expected Auxiliary Space : O(N), N is the number of stones
- Constraints:
- 1 <= n < 10^5 (where n is the length of the array)
- -1000 <= arr[i] < 1000
- ------------------------------------------------------------------------------------------------------------------------------------
- class Solution{
- public:
- bool isBad(vector<int> &arr, int curr, vector<string> &states){
- if(curr>=arr.size() || curr<0 || states[curr]=="GOOD"){
- return false; // not bad
- }
- if(states[curr]=="PROCESSING" || states[curr]=="BAD"){
- return true; // bad
- }
- states[curr]="PROCESSING"; // NODE UNDER PROCESS
- bool answer=isBad(arr,curr+arr[curr],states);
- if(answer==true){
- states[curr]="BAD";
- }
- else{
- states[curr]="GOOD";
- }
- return answer;
- }
- int goodStones(int n,vector<int> &arr){
- vector<string> states(n,"NULL");
- for(int i=0;i<n;i++){
- if(states[i]=="NULL"){
- isBad(arr,i,states);
- }
- }
- int res=0;
- for(auto c: states){
- if(c=="GOOD"){
- res++;
- }
- }
- return res;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment