Created
June 14, 2020 14:44
-
-
Save shubham1710/e25943cd419754911aff78e774fc4c26 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
bool hasSingleCycle(vector<int> array) { | |
int numElementsVisited = 0; | |
int currentIdx = 0; | |
while (numElementsVisited < array.size()) | |
{ | |
if (numElementsVisited > 0 && currentIdx == 0) | |
return false; | |
numElementsVisited++; | |
currentIdx = getNextIdx(currentIdx, array); | |
} | |
return currentIdx == 0; | |
} | |
int getNextIdx(int currentIdx, vector<int> array) | |
{ | |
int jump = array[currentIdx]; | |
int nextIdx = (currentIdx + jump) % (int)array.size(); | |
return nextIdx >= 0 ? nextIdx : nextIdx + array.size(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment