Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
In C++ alternative solution, negative index calculation should be corrected.

Kai

Apr 1, 2025

The alternative solution should be corrected like the first solution.

It should cast the arr.size() to int to mod with negative value.

Without casting, mod result will be affected by overflow because of signed status difference between int & size_t

int nextIndex = (currentIndex + arr[currentIndex]) % (int)arr.size(); if (nextIndex < 0) { nextIndex += arr.size(); // wrap around for negative numbers }

0

0

Comments
Comments

On this page