I tried to solve the next problem from geeksforgeek website. Given an array of size n where all elements are in range from 0 to n-1, change contents of arr[] so that arr[i] = j is changed to arr[j] = i. I saw a solution using modulo:
during one scan arr[arr[i]%n] += n*i and in the next scan arr[i]/=n
his explanation:
What i did here was this, I knew that every location will have an element less than n since it has to represent an index of the array, For any number x, such that x is less than n, x%n = x basically when i write, arr[arr[i]%n] and if arr[i]=j i'm accessing the element at arr[j] now you'll notice , i'm incrementing each such element with n*i at this step, i'm storing two elements in one location, For eg: suppose arr[2]=5 and arr[5]=4 and there are 6 elements in total i'll make arr[arr[2]%6]=arr[5%6]=arr[5]= 4+12 i.e. 4 + 2*6 which is equal to 16 now this contains both the numbers, if i wan't the original number, i.e. during the first scan when i'm changing all the values, i write arr[5]%6 = (4 + 2*6)%6 = 4%6 + 2*6%6 = 4 + 0 = 4 and during the second scan, when i want to update the array to the final resultant arr[5]/6 = (4 +2*6)/6 = 4/6 + 2*6/6 = 0 + 2 = 2 I hope this explanation helps you, all the best
But I can't understand the logic/math behind it. can someone explain in a mathematical way the logic of the method?