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

0% completed

Vote For New Content
Help with using separate variable for correct index vs accessing directly

Adil

Dec 28, 2023

This approach leads to a infinite loop:

class Solution: def sort(self, nums): i = 0 while i < len(nums): if nums[i] != nums[nums[i] - 1]: nums[i], nums[nums[i]-1] = nums[nums[i]-1], nums[i] else: i+=1 return nums

But if I use a separate variable j = nums[I] - 1

it runs fine

What is the issue?

0

0

Comments
Comments
A
Adil 2 years ago

I think I get what's happening, the assignment doesn't work as we thought because of the nested access. Becomes more clear if we use temp variable to make the swap. It still doesn't work, but it's more clearly visible

On this page