Data structures - With Interview Topics
About Strings: typically an interviewer likes to see strings turned into arrays and then back into strings. Always ask if it is possible you can get something other than a string, like a function, or undefined empty value. If so, first thing to do is to check for those edge cases and return 'cannot complete operation' or something. Ask what to return in case of non-string data.
Reverse a string - Ask above questions. Also, check for if length is only 1 character long, in which case nothing should be done.
array.toString() is same as array.join('')
Many ways, do your most natural one first, but be ready to change if asked. Also, talk through your solution and explain the benefits of doing it one over another.
1. basic: backwards for loopfunction reverseString(str){
if(!str || str.length < 2){
return `Cannot reverse ${str}`
}
const backwards = [];
const stringPositions = str.length - 1;
for(let i = stringPositions; i >= 0; i--){
backwards.push(str[i])
}
return backwards.join('')
}
2. array methods (more readable/easy to understand)function reverseString(str){
if(!str || str.length < 2){
return `Cannot reverse ${str}`
}
return str.split('').reverse().join('')
}
3. es6 (w/o checks - as simple as it gets)const reverseString = str => str.split('').reverse().join('')
4. destructuring (w/o checks - simpler still, but may confuse junior devs)const reverseString = str => [...str].reverse().join('')
Basic JS Questions: 1. Given a string, return how many of each letter is in the string.
1A. Given a string, return the letter that is repeated the most.
Thoughts- Ask interviewer: Does capitalization matter?
- Possible Questions Later: Might there be other things like numbers, punctuation or empty spaces in the string?
2. Palindromes
Thoughts- Do you want the return value as true/false, or some other response?
- Ask interviewer:
- Does capitalization matter?
- Should I assume there might be spaces or other characters?
IdeasInstead of using a for loop to compare first and last characters, do a simple string.split('') and compare to the reverse version.
function isPalindrom(str){
let reverseString = str.split('').reverse().join('')
return str.toLowerCase() === reverseString.toLowerCase()
}
3. FizzBuzz and all Variations of FizzBuzz
4. Merge two sorted arraysThoughts- Should you keep duplicates?
- What if anything can I assume are the value types of the array? Numbers, strings, undefined?
- should I assume we are getting arrays or should I check for if arrays
- What is the return value you expect? An array?
Ideas
function mergeArrays(array1, array2){
if(!Array.isArray(array1) || !Array.isArray(array2)){
return 'ERROR: Invalid Input'
}
if(!array1.length) return array2
if(!array2.length) return array1
const mergedArrays = []
let array1Item = array1[0]
let array2Item = array2[0]
let i = 1
let j = 1
while(array1Item || array2Item){
if(!array2Item || array1Item < array2Item){
mergedArrays.push(array1Item)
array1Item = array1[i]
i++
} else {
mergedArrays.push(array2Item)
array2Item = array2[j]
j++
}
}
return mergedArrays
}
tests:console.log(mergeArrays([1, 2, 6], [2, 4, 9]).toString() === [1, 2, 2, 4, 6, 9].toString())
5. Practice these LeetCode Array Questions6. Duplicates- When checking if there are duplicate items in an array, it is best to use a hash table to check, rather than having a loop within a loop.
- Steps: Create blank object. Loop the array and let tempValue = the current iteration. Then do a simple 'if statement' to check if that hash already exists, if it does return true, else add that to the hash.
- Don't forget to return false if there are no matches
Google Question!Find the first repeating character in an array...findFirstRepeatingCharacter = arr => {
const hash = {}
for(let i = 0; i < arr.length; i++){
if(hash[ arr[i] ] !== undefined){
// if(hash[ arr[i] ]){ hash[arr[i]] will return the index position, if the index position is 0 the if statement will equate to false
return arr[i]
} else {
hash[arr[i]] = i
}
}
return 'no characters repeated'
}
Binary Search - searching of a sorted arrayThis search method is used when the values of an array are listed in order. For instance, if you have the first 50 prime numbers starting at 1 listed in order. Say the question is to use binary search to find the position of the given value.
This is an answer that uses a recursive function to find its answer.
Pass into the function: the array, the start position, the length of the array - 1, and the item you are looking for.
0. check if the beginning of the passed in array is greater than or equal to the end of the passed in array, if it isn't return -1, else, continue...
1. Get and save the average of the start position and the array length and floor it
2. Check if the value at that average index is what you are looking for, if it is, great, return that index number!
3a. if it is higher, recurse with: the array, the saved mid point + 1, the original length of the array - 1, the value you are looking for
3b. if it is lower, recurse: the array, the passed in low point, the mid point - 1, the value you are looking for
function binarySearch(arr, start, end, item){
if(end >= start){
let mid = Math.floor(start + (end - 1) / 2)
if(arr[mid] === item) return mid
// this means the item is higher than the middle index
if(arr[mid] < item){
return binarySearch(arr, mid + 1, end, item)
}
return binarySearch(arr, start, mid - 1, item)
}
return -1
}
Basic JS Question: What happens in this problem, why, and how to fix it?
for (var i = 0; i < 3; i++) {
setTimeout(function() {
console.log(i);
}, 1000);
}
Answer: This is a typical question to see if the person has an understanding of the event loop, as well as the difference between the var and let.
What happens and Why?: In the event loop, with every iteration above i gets set as a result of the var. So it will first be stored as 0, then 1, then 2, then 3. It will end on 3 because it gets the value of 3 and then doesn't run because 3 is not less than 3, but the final value of i will be 3.
Also, with each iteration the anonymous function from setTimeout gets sent to the web api and waits 1 second. After a second it is sent to the callback queue, eventually leading to 3 of the same functions waiting in the callback queue. When the for function finishes running, it clears off the stack making room for the functions in the callback queue to be released. When the first one runs it looks for the value of i, which ended at 3, so it will print 3 to the console, so will the next one and the next one.
This happens because var gets set in the function scope, outside of the for loop, so every time it changes its value, within the function the value gets reset.
How to fix it?: Easy, change var to let. But why does this work? Because let only defines a variable in the block scope, in this case, within the for loop. So for each iteration a value of i gets created and is stored in a closure to be used in the function where it was it called.
Let works because on each iteration the value of i is created and store in a closure within the anonymous callback function, so eventually when the anonymous function hits the callstack it will first look to its closure for the value it is looking for.
Array Methods - It certainly doesn't hurt to polish up on ES6 and anything that involves iteration over arrays.
React - class vs functional components (with examples),
- functional components don't have state, though they do accept props
- class extends Component
HOC - understand what a HOC is (and provide an example as well)
- React form of composition. A higher order component will take a component and return the component but with some added functionality or features
- redux connect function is a hoc ... connect(mapStateToProps)(Component)
-
good resource on hocState and Props - have a clear understanding of state (and state management) and props
Lifecycle Methods - have a thorough understanding of lifecycle methods (how and when to use them!)
Arrow functions - know what an arrow function and how it differs from a standard function
Promises - async/await and Promises
Parent/child component relationship - understand how a child component communicates or affects change in the parent.
- Child-to-parent communication is a little more complicated. The standard way of doing this is to have the parent pass a function to the child through props. The child then calls this function at some point and passes it a value that the parent is supposed to react to or use in the function that was sent/called via props. We then write the functionality for the parent's reaction inside the parent component.
-
source for above paragraph and examples
Javascript related...
Is javascript an OOP language?
- no, but it tries to be sometimes
What is functional programming?
- the concept of using pure functions to build software
What is a pure function? - a function that given the same inputs will always return the same output
- a function that returns data without side effects
- a function that does not use shared state, meaning, it only uses data that was passed in as an argument, or that was created within its scope. It does not call properties from outside its scope, which might have been changed since the functions last calling, this would make the outcome of the function unpredictable.
What is a side-effect?
* any time something in a function affects anything outside of its scope
- when a function mutates data outside of its scope
- when a function triggers any external process
- when a function writes to the screen, console, or file
- when a function calls any other function that has side effects
* see Eric Elliott's
article and section on Side Effects
Higher Order Function - any function that takes in a function as an argument or returns a function, or both.
Best resource on functional program, by Eric Elliott
Inheritance vs Composition - Go! (pretty open ended :( ....) -
Fun Fun Functions Explanation -
inheritance is a crappy pattern bourne out of the OOP movement, it makes agile programming problematic. Inheritance depends on building object types. For instance, an animal type, or a robot type. Then you create a new animal or robot and it 'inherits' all the properties of animal or robot. The problem with this is if a year from now you get some request to go back into the program because your boss wants a robotDog, now what? You will likely have to do some bad programming technique like repeat yourself, or you will have to change the structure of the entire application, which would be a nightmare. Instead, programs should be built using composition from the start, not inheritance. It is a poor pattern that leads to problems. Composition uses functions that do one thing. They take in a state and return a value to be used in another function. Redux actions are built using composition. They take in state and return an object, which gets dispatched to another function (a reducer).
Composition - The input of one function comes from the output of another function. Promises are the best example of composition. You return a value, either reject or resolved, which is then passed to .then(), which can return another iteration that can be passed to another .then() function. Also, every time you chain functions you are composing, like... arr.map().slice().split().join(), or whatever.
Read
this by Eric Elliott on function and object composition.
What are some obstacles you've encountered in development and how did you overcome them?What is the biggest developing challenge you've encountered thus far and what was your solution?Focus on your strengths and be forthright with what you don't know - be confident and honest and it will pay off.Google questions...
Why is a manhole cover round?Answers:
1. A circle can not fall through another circle, therefore protecting any workers below. A square can be turned corner to corner and fall through.
2. Because manhole covers are so heavy, being a circle makes them easier for workers to move about, they simply have to roll them.
Clock arm angle questions
Palindrome, binary search tree, graph search, but sometimes they reword they question, always try to use key value pairs(hash table), data structures, JavaScript, DOM manipulate, basic css, check glassdoor questions.
How the web works... What happens behind the scenes when we type http://google.com and hit enter
Big-O questions and searching.
...