Coding Interview Questions Set 3
Coding Interview Set 2.
Let's begin with set 3,
a)Simple recursive solution:
function reverseList(head) {
if (!head || !head.next) {
return head;
}
var newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
b)Iterative solution:
function reverseList(head) {
var prev = null;
while (head) {
var next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
}
8)Given a column title, return its corresponding column number. (Asked in Microsoft)
Write a function that accepts a string s.
Constraints:
1 <= s.length <= 7
s consists only of uppercase English letters.
s is between "A" and "FXSHRXW".
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
Example 1:
Input: "A"
Output: 1
Example 2:
Input: "AB"
Output: 28
Example 3:
Input: "ZY"
Output: 701
Solution:
var titleToNumber = function(s) {
const charCodeBase = 'A'.charCodeAt(0);
const n = s.length;
let result = 0;
for (let i = 0; i < n; i++){
result = result * 26 + (s.charCodeAt(i) - charCodeBase + 1);
}
return result ;
};
The charCodeAt() method returns the Unicode of the character
at the specified index in a string.
Logic:
Think of it as base 26.
For example,
Column number of "AB" = 1 * 26^1 + 2 * 26^0
I hope you like this article.
Please stay connected for coding interview questions set 4.
Saurabh Joshi
Comments
Post a Comment