For loop logic, can someone explain?

can someone explain the logic behind this line in the first for loop?

(str.length - wordsCount * wordLength) + 1

Type your question above this line.


Hello @Jennifer_Herrarte

Let’s understand the logic with the help of an example. Let’s suppose str is catfoxcat and words to look for are ["cat", "fox"]. str.length would be 9 and wordsCount will be 2 and wordLength will be 3. Hence, the total length for words to look for becomes 3*2 = 6.

So essentially, at every index we will be checking if the next 6 characters (including the current one) match the words. But we also have to take care of index out of bounds error. For instance, if we are at the last index we cannot check for next 6 indices.

So this condition just specifies how many iterations we can make on str and match the total length of words in the list. In this case, we can move 4 times as follows:

  1. catfox
  2. atfoxc
  3. tfoxca
  4. foxcat

So loop will run from index 0 to index 3 only.

Hope this helps!

1 Like

this is a great explanation, thank you!!!

Course: Grokking the Coding Interview: Patterns for Coding Questions - Learn Interactively
Lesson: Solution Review: Problem Challenge 4 - Grokking the Coding Interview: Patterns for Coding Questions

1 Like