Code Interview Tips
Each code interview post starts with some tips to help get you through coding interviews. Each writer has had their own experience with interviewing code candidates; I will provide my experience and things I’ve noticed from both good and not-so-good interviews.
- Ask the recruiter if the topic of the coding interview is known. Knowing if the coding interview will be related to structures, algorithms, general knowledge, or other topics helps mentally prepare you and focus your study material.
- Practice coding as often as possible. Websites such as HackerRank, CodeWars, and Excercism.io are free resources at your disposal.
- Use comments, practice OOP, and be ready to explain your reasoning.
- Communicate with your interviewer. We evaluate you on how well you communicate and work as a team when overcoming an unfamiliar problem.
- Struggle without asking for help
- lose your cool
- Use an inappropriate programming language. If you are being asked to do node trees and you choose bash (this happened to me), then you might have a tough time!
The Code Question
Given an array of X elements, sort the first Y number of elements of the array. Print the sorted elements followed by the unsorted elements. Y is a random number from 1 to the length of the array.
import random aSortMe = [90,31,12,15,1,100,6] iYelements = random.randint(1,len(aSortMe)) iUnsorted = len(aSortMe) - iYelements toSort = aSortMe[:iYelements] toSort.sort() print(toSort+aSortMe[-iUnsorted:])
Is the code optimized? No. A lot of interviewers will immediately ask how you would improve the code. I like leaving room for improvement, but this is also a brute-force method. You only have a limited amount of time to show the interviewer you can handle pressure and get something off the ground to improve upon. So let’s talk about the code.
I chose Python this time, though I’m a C++ person and not the one who writes Python articles on this site. I chose Python because of its blatant focus on data manipulation. It’s often used in data science, after all. Displaying x amount of elements in an array does not require me to loop through anything. I created a variable to see how many I am sorting. What might not be obvious is what iUnsorted means. In Python, you can use : and :: with a prefix or suffix integer to display x elements. I know how many to sort, but I need to know what is left. I had to create a second array because if I sort the original array, then I no longer have data integrity, and my slice will not have the right numbers.
So, how to improve? For starters, I’d make a function called SortArray. Code reuse is important; creating functions allows more dynamic use of sorting. I would also solicit input from the user or accept command line arguments. Customer focus is imperative in top-level organizations. Allowing the user to decide what elements go into the system and what to sort by is one way to show customer focus.