Skip to content

Instantly share code, notes, and snippets.

@shubham1710
Created June 14, 2020 14:44
Show Gist options
  • Save shubham1710/e25943cd419754911aff78e774fc4c26 to your computer and use it in GitHub Desktop.
Save shubham1710/e25943cd419754911aff78e774fc4c26 to your computer and use it in GitHub Desktop.
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