Sign in
Log inSign up

Whiteboard is hard: an interview question I solved at home

Samurai Kid 2019's photo
Samurai Kid 2019
·Feb 13, 2019

Today I was in an interview. For me the easy part is the introduction; Telling about myself, what I did in previous jobs and showing my portfolio. However, when it gets to whiteboard questions I am getting stress.

The interview went well at the beginning but the last 30 minutes were terrible. I was asked the following question:

Given an array and d, the number of time to shift items to left, return the new shifted array. SPACE complexity is N (number of items in the array) RUNTIME complexity has to be N

Needles to say I didn't pass. The question is not hard I just was too nervous. At home, I sat and tried to figure out how to solve it and this is how I did it.

Note: I might be wrong, so if you think the solution is missing something please leave a comment.

In Math there is operation called mod which returns the reminder of a division. For example 4 mod 5 will return 4 while 5 mod 5 and 10 mod 5 will return 0.

Now given an array of size M and we want to move its items N times right and we assume N > M then the last item will have to be in position M+N but such a position doesn't exist so we need to wrap it around. Thus its new position will be (M+N) mod M.

That's for the right shifting. To shift left I did a trick. If I want to shift the first item in the array left it is like I'm shifting it (M-1) times right. The same goes to all other items.

In conclusion in order to know the next position of item in the array after d shifting right I have to calculate the following: Pn = (P + [La-1]*d)%(La) where La is the length of the array and P is the current position of the item.

I could reset a new array and store the values there and now I satisfied their requirements. Although, I think I can just swap between items: Getting the new position of the first item, then getting the next position of the item that the first item replaced and so on.

Hassle-free blogging platform that developers and teams love.
  • Docs by Hashnode
    New
  • Blogs
  • AI Markdown Editor
  • GraphQL APIs
  • Open source Starter-kit

© Hashnode 2024 — LinearBytes Inc.

Privacy PolicyTermsCode of Conduct