⏱ 0:00est. 9 min
Merge Intervals
// https://github.com/6chinwei/rakuten-interview-test/blob/master/rakuten-interview-test.js
/*
Q3. Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
Example 1:
Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].
Example 2:
Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16].
This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].
*/
let input = [[1,3], [2,5], [6,9]];
input = [
[3, 5], // min 3, max 5
[1, 3],
[7, 9]
]; // output [[1,5], [7,9]];
//let input = [[1,2],[3,5],[4,9],[6,7],[8,10],[12,16]]
let result = [];
let intervals = input.slice();
intervals.sort((a, b) => a[0] - b[0]);
for (let i=0; i<intervals.length; i++) {
if (intervals[i+1] && intervals[i+1][0] <= intervals[i][1]) {
intervals[i+1][0] = Math.min(intervals[i+1][0], intervals[i][0]);
intervals[i+1][1] = Math.max(intervals[i+1][1], intervals[i][1]);
} else {
result.push(intervals[i]);
}
}
console.log("********** SOL-3 ************")
console.log(result);
/**
Q1 Write a function that takes a string as input and returns the string reversed.
Please implement reverse function or method by yourself .
Example: Given s = "hello", return "olleh"
**/
function reverse(str) {
return str.split("").reverse().join("");
}
console.log("********** SOL-1 ************")
console.log(reverse("hello"))
/**
Q2. Given a positive integer num, write a function which returns True if num is a perfect square else False.
Note: Do not use any built-in library function such as sqrt.
Example 1:
Input: 16
Returns: True
**/
function isPerfectSquare(num) {
for (i=1; i*i<=num;i++) {
// if (i*i == num)
if (num%i === 0 && num/i === i) {
return true;
}
}
return false;
}
console.log("********** SOL-3 ************")
console.log(isPerfectSquare(4));
/**
Q4. Given a 2D board and a word, find if the word exists in the grid.
For example,
Given board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
word = 'ABCCED', -> returns true,
word = 'SEE', -> returns true,
word = 'ABCB', -> returns false.
**/
var board = [
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
];
function isWordExisting(word) {
var found = false;
let n =3, m = 4;
let i = 0, j = 0, k=0;
while (i<n) {
j=0;
while(j<m) {
k=0;
if (board[i][j] === word[k]) {
console.log(word[k]);
k++;
while(k<word.length-1) {
if (i+1 < n && j < m && board[i+1][j] === word[k]) {
console.log(word[k]);
i++;
} else if (i < n && j+1 < m && board[i][j+1] === word[k]) {
console.log(word[k]);
j++;
} else {
break;
// return false;
}
k++
}
if (found) {
return true;
}
}
j++;
}
i++;
}
return false;
}
console.log("********** SOL-4 ************")
// console.log(isWordExisting('ABCCED'));
// console.log(isWordExisting('SEE'));
console.log(isWordExisting('ABCB'));