⏱ 0:01est. 30 min
Rakuten
What are actions and action creators
An action is simply an object that has two things: a type, and a payload.
An action creator is simply a function, that just returns an action.
what are reducers
useMemo, useEffect, useCallback?
https://stackoverflow.com/questions/56910036/when-to-use-usecallback-usememo-and-useeffect
how to center the element
why javascript functions are called as first class functions
what are higher order functions
what are higher order components
what's redux?
what's the advantage of SSR over SPA
what's adcanage of arrow functions over functions
what's advantage of async await over promise
-----------
https://github.com/6chinwei/rakuten-interview-test/blob/master/rakuten-interview-test.js
Implement two stacks using a queue
Find number of "similar numbers"
Implement circular linked list
Why rakuten?
Why do you want to join Rakuten? (Asked in every stage)
The pre-compiled questions contains 5 question, for which you will be given 4 minutes each. The programming test will contain an algorithm for you which you have to create a program in any language of your preference.
Please explain your experience...
- optimising for performance
- minifying script
- concatenating script
- writing tests
super easy online coding test. (overlapping squares)
Given an input vector X, first determine the sum of 2^(of each element), then give the shortest vector Y's length which elements' sum equals the input vector. Require some binary-related logic.
/ O(n) operation and O(1) memory. -ve values and and overflow not handled
unsigned sum = 0;
unsigned temp = 0;
vector::size_type sz = A.size();
unsigned i = 0;
for (unsigned i = 0; i < sz;i++)
sum += pow(2, A[i]);
unsigned j = 0;
while (sum != 0)
{
temp = log2(sum);
sum -= pow(2, temp);
j++;
}
return j;
Could we have your name and the reason why you are interested in Rakuten.
Please tell us your technical background and how you will be able to contribute to the success of the company.
What is your greatest strength and how you leverage your strength for peak performance?
This question is for only those who have worked before* Have you ever changed your job?
What are your career goal and career plans?
"Find the area of two intersecting rectangles".
What is your name? Why Rakuten?
What is your greatest strength? How does it helpful in peak performance? Give an Example.
What is your career goal and career plan? How does this job fit for your career plan?
What is your technical background? how do your skills useful in company's success?
Basic questions on data structures like Queue, List, Trees, etc
Basic questions on Computer theory like Markov models, CAP theorem, ACID properties of RDBMS, etc
Basic questions on maths like Fourier transforms, double and triple integrations, partial differentiation and their applications
Basic questions on statistics and probability, like Normal distribution, etc.
Explain a few technical terms like markov chain, singleton, mvc, bloom filter, opportunistic lock, row-level locking
What data structure will you use to keep top 10 spender for your ecommerce site providing you can keep all records in memory?
Write down algorithms. Describe about CouchBase. Describe about autoboxing. Describe things about Java.
What happens when you enter an address in a browser?
What is the difference between inheritance and function overloading?
How to write swap function without using temporary variable?
In an warehouse, you need boxes to deliver products. Each type of box has a fixed capacity. You don't know the amount of product you have to deliver beforehand. What is the minimum amount of boxes you need to keep so that you can deliver any amount of product using minimum number of boxes?
Customer is asking you to change a feature such that it is inefficient for the system. What do you do?
find the standard deviation of an array.
Find the sum of the area of two possible overlapping rectangles.
What happens when you enter an address in a browser?
Your computer looks up the host of the url you just typed. If it exists in your local cache, it uses that information. If not, then it opens a connection and sends a request to the host. If the host sends back the required response, then your browser uses the HTML parser to present the website.
What is the difference between inheritance and function overloading?
Inheritance is creating a new class from a previously created class. Overloading is adding a new parameter to a function that doesn't take that many parameters.
For example:
def string_together(string1,string2)
string_together("abc","cba","xyz")
Customer is asking you to change a feature that is inefficient for the system. What do you do?
I would sit down with the client and explain to them why that change would be inefficient. If they are still insistent on changing it, then I would try to change in a way that is as efficient as possible.
/**
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(input) {
return input.split('').reverse().join('');
}
// TEST
console.log('Q1');
console.log('reverse(\'hello\');', reverse('hello')); // olleh
/**
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) {
// Check all i^2 if i^2 === num, for i < num/2
var result = false, i = 1;
do {
if( i * i > num) {
break;
}
else if( i * i === num) {
result = true;
break;
}
i++;
} while (i <= num/2); // n + n < n^2 (for n > 2)
return result;
}
console.log('Q2');
console.log('isPerfectSquare(1);', isPerfectSquare(1)); // true
console.log('isPerfectSquare(16);', isPerfectSquare(16)); // true
console.log('isPerfectSquare(14);', isPerfectSquare(14)); // false
/**
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].
**/
// givenInterval: must be an Array of an Array, e.g. [[1,3][6,9]].
// newInterval: must be an Array, e.g. [2,5].
function insertInterval(givenInterval, newInterval) {
// allIntervals = givenInterval + newInterval and sort() by starting number
var allIntervals = givenInterval.slice();
allIntervals.push(newInterval);
allIntervals.sort(function(a, b) {
if(a[0] > b[0]) { return 1;}
else if(a[0] < b[0]) { return -1;}
else { return 0;}
});
var result = [];
for(var i=0; i<allIntervals.length;i++) {
// If the current interval overlaps to the next one, merge current one to the next one.
if(i < allIntervals.length - 1 && allIntervals[i][1] > allIntervals[i+1][0]) {
allIntervals[i+1][0] = Math.min(allIntervals[i][0], allIntervals[i+1][0]);
allIntervals[i+1][1] = Math.max(allIntervals[i][1], allIntervals[i+1][1]);
} else {
// Store the interval that dose not overlap to the next
result.push(allIntervals[i]);
}
}
return result;
}
console.log('Q3');
console.log('insertInterval( [[1,3],[6,9]] , [2,5] )', insertInterval( [[1,3],[6,9]] , [2,5] )); // [[1,5],[6,9]]
console.log('insertInterval( [[1,3],[6,9]] , [4,5] )', insertInterval( [[1,3],[6,9]] , [4,5] )); // [[1,3],[4,5],[6,9]]
console.log('insertInterval( [[1,2],[3,5],[6,7],[8,10],[12,16]] , [4,9] )', insertInterval( [[1,2],[3,5],[6,7],[8,10],[12,16]] , [4,9] )); // [[1,2],[3,10],[12,16]]
// Note. Detail steps for EX 3
// 1. Concat
// [1,2],[3,5],[6,7],[8,10],[12,16],[4,9]
// 2. Sort
// [1,2],[3,5],[4,9],[6,7],[8,10],[12,16]
// 3. Loop and merge
// [1,2],[3,5],[3,9],[6,7],[8,10],[12,16]
// [1,2],[3,5],[3,9],[3,9],[8,10],[12,16]
// [1,2],[3,5],[3,9],[3,9],[3,10],[12,16]
// 4. Only 3 intervals are pushed into results
// [1,2],[3,10],[12,16]
/**
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 result = false;
for(var i = 0; i < board.length; i++) {
for(var j = 0; j < board[i].length; j++) {
// Check the first character
if(board[i][j] === word[0]) {
// Mark this character as the path
markPath(i, j);
// Call the recursive function to find the all characters in the word
if(findNext(i, j, 0, word)) {
// Set result to true if the function find all characters
result = true;
} else {
// Reset the board and then continue the next loop
resetBoard();
}
}
}
}
return result;
// A recursive function
function findNext(i, j, step, word) {
// Return true for the final character
if(step === word.length - 1) {
return true;
}
// Down
if(i < board.length - 1 && board[i+1][j] === word[step+1]) {
markPath(i+1, j);
return findNext(i+1, j, step+1, word);
}
// Up
if(i > 0 && board[i-1][j] === word[step+1]) {
markPath(i-1, j);
return findNext(i-1, j, step+1, word);
}
// Right
if(j < board[i].length - 1 && board[i][j+1] === word[step+1]) {
markPath(i, j+1);
return findNext(i, j+1, step+1, word);
}
// Left
if(j > 0 && board[i][j-1] === word[step+1]) {
markPath(i, j-1);
return findNext(i, j-1, step+1, word);
}
return false;
}
// Change the character to lower case as the path
function markPath(i, j) {
board[i][j] = board[i][j].toLowerCase();
}
// Reset all characters to upper case
function resetBoard() {
for(var i = 0; i < board.length; i++) {
for(var j = 0; j < board[i].length; j++) {
board[i][j] = board[i][j].toUpperCase();
}
}
}
}
// TEST
console.log('Q4');
console.log('isWordExisting(\'ABCCED\')', isWordExisting('ABCCED')); // true
console.log('isWordExisting(\'SEE\')', isWordExisting('SEE')); // true
console.log('isWordExisting(\'ABCB\')', isWordExisting('ABCB')); // false
// Additional:
console.log('Q4 extra');
console.log('isWordExisting(\'CESC\')', isWordExisting('CESC')); // true
console.log('isWordExisting(\'CESCC\')', isWordExisting('CESCC')); // false
/**
Q5. Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
Example:
Given a = 1 and b = 2, return 3.
**/
function add(num1, num2) {
var s1, s2;
s1 = parseNumberToStringWithPN(num1);
s2 = parseNumberToStringWithPN(num2);
// Change number to the string whose length is same as the value. 'p' means positive and 'n' means negative.
// EX. 2 => pp
// EX. -4 => nnnn
function parseNumberToStringWithPN(num) {
if(num >= 0) {
return 'p'.repeat(num);
} else {
return 'n'.repeat(num*-1);
}
}
// If one number is positive and another is negative, using substr() to both strings until anyone's length to be 0
if((num1 < 0 || num2 < 0) && !(num1 < 0 && num2 < 0)) {
do {
s1 = s1.substr(1);
s2 = s2.substr(1);
} while(s1.length > 0 && s2.length > 0);
}
// Use concat() for adding two variables
var result = s1.concat(s2);
if(result.indexOf('n') > -1) {
// Negative result
return result.length * -1;
} else {
// Positive result
return result.length;
}
}
// TESTS
console.log('Q5');
console.log('add(1,2)', add(1,2)); // 3
console.log('add(1,-2)', add(1,-2)); // -1
List sorting algorithms.
How to reverse a string without using extra memory?
Print recursively..
public void reverse(char s[]){
for(int i=0,j=s.length-1;i<=j;i++,j--){
s[i] ^= s[j];
s[i] ^= (s[j] ^= s[i]);
}
}
What happens when you enter an address in a browser?
Your computer looks up the host of the url you just typed. If it exists in your local cache, it uses that information. If not, then it opens a connection and sends a request to the host. If the host sends back the required response, then your browser uses the HTML parser to present the website.
What is the difference between inheritance and function overloading?
Inheritance is creating a new class from a previously created class. Overloading is adding a new parameter to a function that doesn't take that many parameters.
For example:
def string_together(string1,string2)
string_together("abc","cba","xyz")
Customer is asking you to change a feature that is inefficient for the system. What do you do?
I would sit down with the client and explain to them why that change would be inefficient. If they are still insistent on changing it, then I would try to change in a way that is as efficient as possible.
how can u deal with multiple queries in db?
rectilinear problem on codility
http://www.conceptualdynamics.com/files/rec/rec_solve_page0.htm
rectilinear intersection problem.
public static int rectilinear(int k, int l, int m, int n, int p, int q, int r, int s) {
int areaA = (m - k) * (n - l);
int areaB = (r - p) * (s - q);
int totalArea = areaA + areaB;
// check if rectangles intersect
if (k p && l q) {
int intersectionX1 = Math.max(k, p);
int intersectionX2 = Math.min(m, r);
int intersectionY1 = Math.max(l, q);
int intersectionY2 = Math.min(n, s);
int intersectionArea = (intersectionX2 - intersectionX1) * (intersectionY2 - intersectionY1);
totalArea = totalArea - intersectionArea;
}
if (totalArea < 0) //it probably did a wrap-around and is greater than Integer.MAX_VALUE
{
return -1;
}
return totalArea;
}
https://stackoverflow.com/questions/4549544/total-area-of-intersecting-rectangles
https://leetcode.com/discuss/interview-experience/390201/rakuten-senior-software-engineer-bangalore-august-2019-offer
https://github.com/6chinwei/rakuten-interview-test/blob/master/rakuten-interview-test.js
https://github.com/SlawaGurevich/Rakuten-Coding-Test
https://github.com/binghuan/MyRakutenSingapore
https://github.com/binghuan/CodingQuestions/tree/gh-pages/leetcode
https://github.com/mosdeo/Rakuten-Codility-Test/blob/master/main.cpp
https://leetcode.com/problems/container-with-most-water/submissions/
https://leetcode.com/explore/interview/card/top-interview-questions-easy/92/array/564/#.YH87HT-qLro.twitter
https://leetcode.com/explore/interview/card/top-interview-questions-easy/92/array/727/#.YHoXmTOpbvA.twitter
https://leetcode.com/problems/non-decreasing-array/submissions/
https://github.com/WebHero0544/books/blob/master/Professional.JavaScript.for.Web.Developers.4th.Edition.2019.10.pdf
https://github.com/danielmascena/dojo
https://www.hackerrank.com/danielmascena?badge=problem-solving&stars=4&level=2&hr_r=1&utm_campaign=social-buttons&utm_medium=twitter&utm_source=badge_share&social=linkedin
https://twitter.com/mascnda/status/1321201620810608644
The Codility Test was about taking an integer and determine how many different arrangements of the number are possible. So if given, 132, arrangements are 132, 123, 231, 213, 312, 321. So the function should return 6.
- Difference between MySql and Postgres
- Describe a data pipeline (aggregation, enrichment etc) for a specific business scenario
- https://leetcode.com/problems/word-break-ii
- Concurrent data structures, strings, array, tree traversal, class design
- Find Kth largest element in an array.(max-heap)
- Find start of a rotated-sorted array
- what is the number tables required for 1-1 mapping, n-1 mapping, n-m mapping.
- Shortest winter days.
- Root to leaf path with maximum distinct nodes.
- shift elements of a single dimensional array in the right direction by one position
- Binary tree, create own linked list impl, sorting algo, design a vending machine
- What is immutable objects their properties and how you can make a queue as immutable?
- How to implement JWT for securely sharing the resources in your application
- Problem solving question : find the min distance between the duplicate element present in the array.
- How to implement custom properties file in spring boot project and spring annotations related questions
- How to use JUnit to test the endpoints in spring boot app? What is the use of mockito
- Asked questions related to UNIX commands like grep , cp etc
- Find the Kth largest number in an array.
- How do you decide between SQL and NoSql
We are thinking to arrange meeting room.
Unfortunately, the wall between rooms is not sound proof perfectly. So You can hear other room's noise when you are using your room. So you are unhappy always.
What we can do here is based on given rooms and users, how to arrange room separately so people dont feel unconfortable.
[Row, Column, number of users you need to assign the room]-> unhappy point
ex.
[2, 3, 6] -> 7
[4, 1, 2] -> 0
[3, 3, 8] -> 8
https://github.com/binghuan/MyRakutenSingapore/blob/master/CodingTest_2/meetingRoomArrangment.js
- List as many different implementations of the Collection interface as you can think of.
- what different between hashtable and hashmap
- Basic questions on multi-threading, how to implement it, how to kill a thread, use of volatile keyword.
- methods in object class, details on usage of all and how to over ride equals & hash code.
- types of Algorithms and their performance
- Design patterns types and how you have used in past.
- few question on UNIX like how to identify which application is running on a specific port, how to identify which is writing to a file.
- Finding out the area of the intersection of two rectangles
- Bitwise XOR of all the numbers between two integers (like 5 and 8 are inputs the o/p should be 5 BitwiseXor 6 BitwiseXor 7 BitwiseXor 8)
- Onsite task to prototype an elevator panel for 1000 floors.
https://github.com/charindu/rakuten/blob/master/pingponggame.js
https://github.com/rlaxodus/RakutenTest/blob/master/ISBNConverter.java
https://www.geeksforgeeks.org/check-instance-15-puzzle-solvable/
https://leetcode.com/problems/battleships-in-a-board/description/
https://github.com/mcustiel/PlayingCodility/blob/master/src/main/java/org/mcustiel/codility/Battleship.java
https://www.youtube.com/watch?v=zSQIGzmcp2I&ab_channel=Devpost
Present Status: Developer Associate, SAP Labs India
Position: Senior Software Engineer
Location: Bangalore, India
Interview Experience
Technical Screening Round(Face-2-Face)
Questions on paper published during college - merge sort
Questions on whitepaper published at SAP - JEE vs Springboot
Check for a loop in linked list
Given a linked list swap elements in pairs in place:
Input - 1->2->3->4->5
Output- 2->1->4->3->5
Write code for this
Technical Round 2 (Face-2-Face)
Given a number, return the next biggest anagram number
Input - 123
Output - 132
Write code
Write code for BFS of a binary tree
Lambda operator and sample code for showing lambda
SQL query:
Employee - empId, empName,deptId
Department- deptId, deptName
Write SQL query to return all departments and number of employees for that dept.
There may be depts with 0 employees as well
Technical Round 3 - System Design (Face-2-Face)
Design an application like google Keep.
Main features:
Add a note
Edit a note
Delete a note
Add/Delete tags
Each note can have multiple tags
Search on tags
Design DB tables, API design and Java POJOs
User constraints:
Around 10K users
Each user has around 1K notes - 100 accessed frequently
900 not so freq accessed
SQL Db vs NoSQL DB
What will you do when your DB size is almost full?
Related questions on sharding, consistent hashing
Managerial Round - over call
What type of data structure will you use for designing a scheduler? How do you set priority. Sample sudo code for the same
How do you define a TTL cache?
Given a class Employee - ID, name, data[]
Create hashcode and equals method for this class.
How will it affect if EmpId is not unique. Or if it is unique
Department Head - over call
Design the "tail" method used in linux.
Basically there is a log file whch is of huge size, millions may be and you have to retrieve the last 'n' lines from the log. The actual log file is dynamic. That is while you are reading the log file, there may be new additions to the file as well and that should be incorporated into the solution.
Basic behavioural questions
--------
There are 4 steps.
1. To do code test for initial screening
2. Once 1st is passed, there will be zoom interview with 2 engineers. Each session will take 1 hour.
3. Once 2nd is passed, there will be system design interview
4. Cultural and Behavior Test
They did not update you with the interview result if you are not passed the 2nd interview. So do not expect much.
Interview Questions
Q1: Easy question on code test
Q2: Easy question on another code test
Q3: Networking
Q4: Concurrency
Q5: Database Indexing
------------
How to sync user data in the multiple devices?
Write a script to to test for duplicated content on viki home page
HTTP and Networking Knowledge
Database tuning
--------------
Interview Questions
1. General Questionnaire to collect personal information.
2. Take-home task: Scrape Viki homepage to find duplicate content.
3. Tech questions on web technologies
- What would be the output of code snippet (recursive function).
- What is your understanding of sprites/fonts/mvc/cors/csrf/closure/promise/restful etc
4. Puzzle: 25 horses. 1 stadium with 5 tracks. Could only race 5 horses at a time. Find fastest and second fastest.
https://mindyourdecisions.com/blog/2017/05/11/can-you-solve-the-25-horses-puzzle-google-interview-question/
https://www.geeksforgeeks.org/puzzle-9-find-the-fastest-3-horses/
How would you go about designing schema for a feature, how would you structure/secure/version your APIs,
how would you go about speeding up your DB queries, caching, sharding etchow would you go about speeding up your DB queries, caching, sharding etc
-------------
How to test a search engine
-------------
SQL and click through rate
-------------
Scrape their main site and find duplicate content.
-------------
How do you check the memory leak issue?
-------------
How do you check the integrity of the data passed over the network?
- Verify the checksum
https://github.com/binghuan/MyRakutenSingapore/blob/master/CodingTest_2/meetingRoomArrangment.js
/* Concept.
1. Allocate Seat Map for Meeting Room by Width and Height
2. Take number of seats by checking the Neighbor, less is better.
3. Try 2 solutions for taking seat.
Solution [1]: Taking seat from first.
Solution [2]: Taking seat from last.
Do the comparison between solution [1] and solution [2].
Get the min. result for answer.
*/
const DBG = false;
let seatMap = [];
let seats = {};
let getSeatStateAfterTaking = function (x, y, width, height) {
let seat = seats[x + "," + y];
if(DBG)console.log("#seatMap:", seatMap);
let numberOfNeighbor = 0;
// check neighbor
if (x - 1 >= 0) {
if (seatMap[x - 1][y]) {
if(DBG)console.log("!Left");
numberOfNeighbor += 1;
}
}
if (x + 1 < width) {
if (seatMap[x + 1][y]) {
if(DBG)console.log("!Right", seatMap[x + 1, y]);
numberOfNeighbor += 1;
}
}
if (y - 1 >= 0) {
if (seatMap[x][y - 1]) {
if(DBG)console.log("!Up");
numberOfNeighbor += 1;
}
}
if (y + 1 < height) {
if (seatMap[x][y + 1]) {
if(DBG)console.log("!Down");
numberOfNeighbor += 1;
}
}
if(DBG)console.log(">> getSeatStateAfterTaking: ", numberOfNeighbor);
return numberOfNeighbor;
}
let emptySeatMap = function (width, height) {
// 1st initialize seets .
seatMap = [];
seats = {};
for (let i = 0; i < width; i++) {
seatMap[i] = [];
for (let j = 0; j < height; j++) {
let coordinate = String(i).concat("," + String(j))
seats[coordinate] = {
neighbor: 0,
x: i,
y: j
}
seatMap[i][j] = 0;
}
}
}
let arrangeMeetingRoom = function (inputData, isTrial) {
let width = inputData[0];
let height = inputData[1];
let numberOfUsers = inputData[2];
if(DBG)console.log("## INPUT: ", width, height, numberOfUsers);
emptySeatMap(width, height);
if(DBG)console.log("seatMap: ", seatMap);
if(DBG)console.log("seats: ", seats);
let minNumberOfNeighbor = 5;
let posX = -1;
let posY = -1;
let checkingCounter = 0;
for (let k = 0; k < numberOfUsers; k++) {
minNumberOfNeighbor = 5;
for (let i = 0; i < width; i++) {
for (let j = 0; j < height; j++) {
let coordinate = String(i).concat("," + String(j))
if (seatMap[i][j] == 0) {
checkingCounter += 1;
let newNumberOfNeighbor = getSeatStateAfterTaking(i, j, width, height);
if(DBG)console.log("_check seat[", i, ",", j, "]", newNumberOfNeighbor, minNumberOfNeighbor);
if (isTrial && (checkingCounter % 2 == 1) && newNumberOfNeighbor == minNumberOfNeighbor || newNumberOfNeighbor < minNumberOfNeighbor) {
minNumberOfNeighbor = newNumberOfNeighbor;
posX = i;
posY = j;
if(DBG)console.log("--> new seat: ", posX, posY);
}
}
}
}
seatMap[posX][posY] = 1;
seats[posX + "," + posY].neighbor = minNumberOfNeighbor;
if(DBG)console.log("########### Seat [", posX, ",", posY, "] has been taken.");
}
if(DBG)console.log("## INPUT: ", width, height, numberOfUsers);
if(DBG)console.log("@@ANSWER: ");
if(DBG)console.log("seatMap: ", seatMap);
//console.log("seats: ", seats);
// Final Step: Check Neighbor
let count = 0;
for (let i = 0; i < width; i++) {
for (let j = 0; j < height; j++) {
if (j + 1 < height && seatMap[i][j] && seatMap[i][j + 1]) {
count += 1;
}
}
}
for (let j = 0; j < height; j++) {
for (let i = 0; i < width; i++) {
if (i + 1 < width && seatMap[i][j] && seatMap[i + 1][j]) {
count += 1;
}
}
}
if(DBG)console.log("count = ", count);
return count;
}
let testData = "[5,2,8]-> 7 [3,5,14]-> 18 [1,16,1]-> 0 [3,5,1]-> 0 [8,2,12]-> 10 [16,1,1]-> 0 [3,3,6]-> 3 [2,6,12]-> 16 [15,1,0]-> 0 [5,3,7]-> 0 [4,3,5]-> 0 [3,5,11]-> 8 [7,2,13]-> 16 [15,1,6]-> 0 [15,1,15]-> 14 [4,4,9]-> 2 [5,3,8]-> 0 [3,5,6]-> 0 [16,1,7]-> 0 [1,15,7]-> 0 [4,3,12]-> 17 [5,3,13]-> 14 [2,4,5]-> 2 [5,3,5]-> 0 [16,1,16]-> 15 [2,5,8]-> 7 [5,3,4]-> 0 [5,3,10]-> 6 [4,4,7]-> 0 [3,5,9]-> 3 [4,2,2]-> 0 [4,4,15]-> 20 [2,2,4]-> 4 [5,3,11]-> 8 [4,4,8]-> 0 [1,16,9]-> 1 [4,4,16]-> 24 [1,15,6]-> 0 [15,1,8]-> 0 [5,3,6]-> 0 [16,1,9]-> 1 [3,5,15]-> 22 [1,15,1]-> 0 [1,15,0]-> 0 [2,5,9]-> 10 [3,5,10]-> 6 [1,15,15]-> 14 [3,2,0]-> 0 [5,3,2]-> 0 [5,3,1]-> 0 [5,2,4]-> 0 [3,5,4]-> 0 [2,7,13]-> 16 [3,3,0]-> 0 [7,2,11]-> 10 [4,4,0]-> 0 [1,1,0]-> 0 [2,6,9]-> 7 [3,5,3]-> 0 [5,3,15]-> 22 [5,2,6]-> 2 [3,4,12]-> 17 [2,3,6]-> 7 [1,1,1]-> 0 [15,1,1]-> 0 [1,16,16]-> 15 [2,2,2]-> 0 [3,3,9]-> 12 [16,1,8]-> 0 [9,1,6]-> 2 [5,3,12]-> 11 [2,2,3]-> 2 [3,5,7]-> 0 [7,2,0]-> 0 [4,3,6]-> 0 [2,3,4]-> 2 [1,15,8]-> 0 [16,1,0]-> 0 [5,3,9]-> 3 [15,1,7]-> 0 [2,4,6]-> 4 [1,16,7]-> 0 [3,5,12]-> 11 [1,16,8]-> 0 [4,4,1]-> 0 [3,5,0]-> 0 [3,5,8]-> 0 [1,16,0]-> 0 [5,3,3]-> 0 [5,3,0]-> 0 [1,13,9]-> 4 [3,5,2]-> 0 [1,9,6]-> 2 [6,2,12]-> 16 [4,3,8]-> 4 [3,5,5]-> 0 [5,3,14]-> 18 [4,3,7]-> 2 [6,2,4]-> 0 [3,5,1]-> 0";
let testItems = testData.split(" ");
let totalTestCases = testItems.length / 2;
let counter = 1;
let target = -1;
for (let i = 0; i < testItems.length; i++) {
// if(counter != -1 || counter != target) {
// ++i;
// counter+=1;
// continue;
// }
let expectedAnswer = parseInt(testItems[i + 1]);
let answer1 = arrangeMeetingRoom(JSON.parse(testItems[i].split("->")[0]), false);
let answer2 = arrangeMeetingRoom(JSON.parse(testItems[i].split("->")[0]), true);
let answer = answer1;
if (answer2 < answer1) {
answer = answer2;
}
console.log("<!-- RUN TEST CASE #", counter, "/", totalTestCases, "--------------------------->");
console.log("@@@@@ Data for Testing: ", testItems[i], testItems[i + 1]);
if (expectedAnswer != answer) {
console.log("X_X Wrong Answer, expectedAnswer:", expectedAnswer, ", But Your Answer is: ", answer1, answer2);
break;
} else {
console.log("^_^b ! ~ OK");
}
++i;
counter += 1;
}
Codility:
- Shortest winter days.
- Root to leaf path with maximum distinct nodes.
https://github.com/yoondw/Internship_Activity/blob/c85220e94345f1111afe60d7b159fffa60b49616/Rakuten/Rakuten_Crawling.ipynb
https://github.com/swathidbhat/product-reviews/blob/main/Rakuten%20Viki%20Reviews%20-%20Web%20Scraping.ipynb
https://github.com/6chinwei/rakuten-interview-test/blob/master/rakuten-interview-test.js
/**
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(input) {
return input.split('').reverse().join('');
}
// TEST
console.log('Q1');
console.log('reverse(\'hello\');', reverse('hello')); // olleh
/**
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) {
// Check all i^2 if i^2 === num, for i < num/2
var result = false, i = 1;
do {
if( i * i > num) {
break;
}
else if( i * i === num) {
result = true;
break;
}
i++;
} while (i <= num/2); // n + n < n^2 (for n > 2)
return result;
}
console.log('Q2');
console.log('isPerfectSquare(1);', isPerfectSquare(1)); // true
console.log('isPerfectSquare(16);', isPerfectSquare(16)); // true
console.log('isPerfectSquare(14);', isPerfectSquare(14)); // false
/**
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].
**/
// givenInterval: must be an Array of an Array, e.g. [[1,3][6,9]].
// newInterval: must be an Array, e.g. [2,5].
function insertInterval(givenInterval, newInterval) {
// allIntervals = givenInterval + newInterval and sort() by starting number
var allIntervals = givenInterval.slice();
allIntervals.push(newInterval);
allIntervals.sort(function(a, b) {
if(a[0] > b[0]) { return 1;}
else if(a[0] < b[0]) { return -1;}
else { return 0;}
});
var result = [];
for(var i=0; i<allIntervals.length;i++) {
// If the current interval overlaps to the next one, merge current one to the next one.
if(i < allIntervals.length - 1 && allIntervals[i][1] > allIntervals[i+1][0]) {
allIntervals[i+1][0] = Math.min(allIntervals[i][0], allIntervals[i+1][0]);
allIntervals[i+1][1] = Math.max(allIntervals[i][1], allIntervals[i+1][1]);
} else {
// Store the interval that dose not overlap to the next
result.push(allIntervals[i]);
}
}
return result;
}
console.log('Q3');
console.log('insertInterval( [[1,3],[6,9]] , [2,5] )', insertInterval( [[1,3],[6,9]] , [2,5] )); // [[1,5],[6,9]]
console.log('insertInterval( [[1,3],[6,9]] , [4,5] )', insertInterval( [[1,3],[6,9]] , [4,5] )); // [[1,3],[4,5],[6,9]]
console.log('insertInterval( [[1,2],[3,5],[6,7],[8,10],[12,16]] , [4,9] )', insertInterval( [[1,2],[3,5],[6,7],[8,10],[12,16]] , [4,9] )); // [[1,2],[3,10],[12,16]]
// Note. Detail steps for EX 3
// 1. Concat
// [1,2],[3,5],[6,7],[8,10],[12,16],[4,9]
// 2. Sort
// [1,2],[3,5],[4,9],[6,7],[8,10],[12,16]
// 3. Loop and merge
// [1,2],[3,5],[3,9],[6,7],[8,10],[12,16]
// [1,2],[3,5],[3,9],[3,9],[8,10],[12,16]
// [1,2],[3,5],[3,9],[3,9],[3,10],[12,16]
// 4. Only 3 intervals are pushed into results
// [1,2],[3,10],[12,16]
/**
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 result = false;
for(var i = 0; i < board.length; i++) {
for(var j = 0; j < board[i].length; j++) {
// Check the first character
if(board[i][j] === word[0]) {
// Mark this character as the path
markPath(i, j);
// Call the recursive function to find the all characters in the word
if(findNext(i, j, 0, word)) {
// Set result to true if the function find all characters
result = true;
} else {
// Reset the board and then continue the next loop
resetBoard();
}
}
}
}
return result;
// A recursive function
function findNext(i, j, step, word) {
// Return true for the final character
if(step === word.length - 1) {
return true;
}
// Down
if(i < board.length - 1 && board[i+1][j] === word[step+1]) {
markPath(i+1, j);
return findNext(i+1, j, step+1, word);
}
// Up
if(i > 0 && board[i-1][j] === word[step+1]) {
markPath(i-1, j);
return findNext(i-1, j, step+1, word);
}
// Right
if(j < board[i].length - 1 && board[i][j+1] === word[step+1]) {
markPath(i, j+1);
return findNext(i, j+1, step+1, word);
}
// Left
if(j > 0 && board[i][j-1] === word[step+1]) {
markPath(i, j-1);
return findNext(i, j-1, step+1, word);
}
return false;
}
// Change the character to lower case as the path
function markPath(i, j) {
board[i][j] = board[i][j].toLowerCase();
}
// Reset all characters to upper case
function resetBoard() {
for(var i = 0; i < board.length; i++) {
for(var j = 0; j < board[i].length; j++) {
board[i][j] = board[i][j].toUpperCase();
}
}
}
}
// TEST
console.log('Q4');
console.log('isWordExisting(\'ABCCED\')', isWordExisting('ABCCED')); // true
console.log('isWordExisting(\'SEE\')', isWordExisting('SEE')); // true
console.log('isWordExisting(\'ABCB\')', isWordExisting('ABCB')); // false
// Additional:
console.log('Q4 extra');
console.log('isWordExisting(\'CESC\')', isWordExisting('CESC')); // true
console.log('isWordExisting(\'CESCC\')', isWordExisting('CESCC')); // false
/**
Q5. Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
Example:
Given a = 1 and b = 2, return 3.
**/
function add(num1, num2) {
var s1, s2;
s1 = parseNumberToStringWithPN(num1);
s2 = parseNumberToStringWithPN(num2);
// Change number to the string whose length is same as the value. 'p' means positive and 'n' means negative.
// EX. 2 => pp
// EX. -4 => nnnn
function parseNumberToStringWithPN(num) {
if(num >= 0) {
return 'p'.repeat(num);
} else {
return 'n'.repeat(num*-1);
}
}
// If one number is positive and another is negative, using substr() to both strings until anyone's length to be 0
if((num1 < 0 || num2 < 0) && !(num1 < 0 && num2 < 0)) {
do {
s1 = s1.substr(1);
s2 = s2.substr(1);
} while(s1.length > 0 && s2.length > 0);
}
// Use concat() for adding two variables
var result = s1.concat(s2);
if(result.indexOf('n') > -1) {
// Negative result
return result.length * -1;
} else {
// Positive result
return result.length;
}
}
// TESTS
console.log('Q5');
console.log('add(1,2)', add(1,2)); // 3
console.log('add(1,-2)', add(1,-2)); // -1