Unique id generator is a must do system design question. The season being unique id is required in almost every system nowadays.

- What is the length of the unique id? 64 bits
- Is the unique id sortable? Yes
- Is the unique id generated for a distributed system? Yes
- How many unique ids will be generated per-second? 10K
- How many regions or clusters are the in the system? 6

For every new registration an unique id is required for the account. For every photo an unique id is required. For every tweet an unique id is required.

For a multi-master replication setup each server has to generate an unique id and increment it by the number of replication present.

Lets say we have **2 Database Servers**

Server 2 starts its counter from **0000000 + N**

Here **N** is the number of servers in the system.

**Advantages**

- Easy to implement.
- Each server is independent of each other.
- Cost optimised

**Drawbacks**

There are number of problems in this approach. As we are discussing about distributed systems here the number of servers added and removed from the entire stack is dynamic and that causes some serious problems to this architecture.

If we increase or decrease server counts then we will have to update the counters of every server.

The solution is not scalable as when the DB servers are added or removed from the system dynamically, the entire system has to be updated with the new number. If not done correctly then there can be

**collision of IDs.**

Next widely accepted way is to generate UUID using libraries. Below is the HLD of the system.

Each DB Server is generating its own UUID and it has been found that the chance of getting same UUID is once in a billion.

From Wikipedia:

💡 Only after generating 1 billion UUIDs every second for the next 100 years, the probability of creating just one duplicate would be about 50%. Or, to put it another way, the probability of one duplicate would be about 50% if every person on earth owned 600 million UUIDs.So this is pretty much solves the problem but there are some **drawbacks** in this approach as well:

- The length of the string is 128bits while we need 64 bits
- Ids are not built with UTC timestamp its based on CPU Clock Time - thus very hard to sort
- The generated ids can be alphanumeric thus might take longer time to sort

Lets look at a basic HLD of a ticket server

The ticket server is responsible for generating tokens for all the servers that are part of the entire design. Whenever a request will come no matter from which zone the same ticket server will generate the ticket. This approach was widely popularised by Flickr and till date it is widely used across many products in the industry.

If your scale is < 1M users this should be an approach we can consider, but as the system scales this will require some more upgrades.

**Advantages**

```
1. Scales very well with n number of servers
2. Can generate 64 bit Numeric ID since code is in developer control.
3. Very easy of implement using caches and hash tables.
```

**Disadvantages**

```
1. Single point of failure.
2. If made a distributed system then can increase cost of the project.
3. Distributed database problem will then kick in. Problems like data synchronization will happen.
4. This will become a full blown project and if this fails all the dependent Systems will fail.
```

The idea is fairly simple and solves almost all our problems.

To think about this problem we have to divide and conquer the problem and think about what available entities we have.

- Data Centres
- Machines in Data Centres
- Timestamps

**How can we use these values to generate a sortable 64Bit Numeric ID for our system?**
We want to join all of these together and create value that can be identified sorted and scaled.

Here we can divide the 64 bits into sub parts

| Sign bit 1 bit | Timestamp 41 bits | Data centre ID 5 bits | Machine ID 5 bits | Sequence Number 12 bits | | --- | --- | --- | --- | --- | | 0 | 1643943869 | 0 - 32 | 0 - 32 | 0 - 999 |

**Datacenter ID** This is pretty straight forward, We can generate and assign
2 ^ 5 =32 data centre IDs
Generally there's one data-centre per region like US-East, US-Central, IN-Mumbai etc.

**Machine ID:** This is also same we can generate and put 32 machines per data centre.

**Sequence Number**

This number is generated at the runtime.

The total combinations that can be generated is 2 ^ 12 = 4096 combinations per millisecond.

A combination can be generated in multiple ways but in a real system the counter will reset to 0 every second.

*What does that mean?*
If there is more than one id is requested to be created then every millisecond the counter will increase by 1 and by the end of the second the counter will again be reset to 0.

Twitter Snowflake approach is pretty simple and we need to generate a new id by using SIGN BIT, TIMESTAMP, DATA CENTRE ID and sequence number.

We have not considered on how to co-ordinate the timestamp between all the servers. To achieve that precision we have to consider something called as **NTP**

NTP : Network Time Protocol for generating timestamp.

Clock Synchronisation is also required to generate correct logs across multiple data centres. This we can see in practice at Kibana setup by the cloud infra team.

Learn more about it here.

*Twitter Snowflake*

https://en.m.wikipedia.org/wiki/Snowflake_ID

***System Design Primer -** Great resource to prepare for system design interviews.*

https://github.com/donnemartin/system-design-primer

]]>Given an integer array `nums`

, find the contiguous subarray (containing at least one number) which has the largest sum and return *its sum*.

A **subarray** is a **contiguous** part of an array.

**Example 1:**

```
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
```

**Example 2:**

```
Input: nums = [1]
Output: 1
```

**Example 3:**

```
Input: nums = [5,4,-1,7,8]
Output: 23
```

**Constraints:**

`1 <= nums.length <= 105`

`104 <= nums[i] <= 104`

**Follow up:** If you have figured out the `O(n)`

solution, try coding another solution using the **divide and conquer** approach, which is more subtle.

A) Lets consider taking a number that would always be the least number in the entire number system. This is because I want to make sure my first max number is greater than this least number.

B) Lets take a number to store the sum of the elements traversed in the array.

- Initialise a variable sum with 0 to store the sum of contiguous numbers of the array.
- Initialize a variable maxSum and store value which is the least in every case.
Loop through each element of the array

- Add the element with the sum of previous numbers.
- If sum is greater than the maxSum then update the maxSum value with num.
Also check if the sum is less than 0 set it to 0 again.

**Now why is this required?**Theres no point in storing a number less than 0 because we only have to check the greatest number among the negative numbers because if we keep adding negative numbers it becomes the opposite of greatest number.

```
/**
* @param {number[]} nums
* @return {number}
*/
var maxSubArray = function(a) {
let maxSum = -(Math.pow(2, 53) - 1); // A
let sum = 0;
for(let i = 0; i< a.length; i++) {
sum += a[i];
if(sum > maxSum) {
maxSum = sum;
}
if(sum < 0) {
sum = 0;
}
}
return maxSum;
};
```

Now I urge you to read the code and do a dry run in your mind to understand it fully.

You have to keep practising these three variant of this problem to fully understand this and explain this in a real interview

- Return the indices of the contiguous array.
- Return the sub-array.

If you like the content do drop me follow on Twitter learn these concepts with easy.

]]>Given two strings `ransomNote`

and `magazine`

, return `true`

if `ransomNote`

can be constructed from `magazine`

and `false`

otherwise.

Each letter in `magazine`

can only be used once in `ransomNote`

.

**Example 1:**

```
Input: ransomNote = "a", magazine = "b"
Output: false
```

**Example 2:**

```
Input: ransomNote = "aa", magazine = "ab"
Output: false
```

**Example 3:**

```
Input: ransomNote = "aa", magazine = "aab"
Output: true
```

**Constraints:**

`1 <= ransomNote.length, magazine.length <= $10^5$`

`ransomNote`

and`magazine`

consist of lowercase English letters.

If ransom note is bigger than magazine, then its not possible to create a substring. So, return false.

I am looking for a way where I can use the occurrence count of each letter of ransom note and match it with magazine's each letter occurrence count.

Suppose I take the letter "a" from ransom note and store the occurrences of "a" in a map, and while I traverse through magazine I will also store the occurrence of "a" in another map.

If count of magazine's "a" is greater than or equal to ransom's "a" count then we can create the word, else return false.

```
/**
* @param {string} ransomNote
* @param {string} magazine
* @return {boolean}
*/
var canConstruct = function(ransomNote, magazine) {
if(ransomNote.length === 0 || magazine.length === 0) {
return false;
}
if(ransomNote.length > magazine.length) {
return false;
}
// { key : character , value: countOfOccurrence};
let hasMap = {};
// 1st: Create the Map with magazine's character occurrence and count.
for(let m = 0; m < magazine.length; m++) {
const magChar = magazine[m];
if( hasMap[magChar] !== undefined ) {
hasMap[magChar] += 1;
} else {
hasMap[magChar] = 1;
}
}
/*
Now your map has been created
So, now you have to:
1. find values of ransom note's characters in the map
2. Reduce the count of the character(key)'s value by 1
3. Check if the count of the character is 0 or less than 0
4. If its less than 0, clearly ransom note can't be made.
*/
let isPossible = true;
for(let r = 0; r < ransomNote.length; r++ ) {
const ranChar = ransomNote[r];
if(hasMap[ranChar]) {
hasMap[ranChar] -= 1 ;
if(hasMap[ranChar] < 0) {
isPossible = false;
break;
}
} else {
isPossible = false;
break;
}
}
return isPossible;
};
```

I hope you got a new perspective of solving this problem easy in O(n) time complexity.

If you are JavaScript Developer and want to get into top tech company, follow me on Twitter.

👇🏻👇🏻

I tweet and write about Data Structures and Algorithms, System Design and Large Scale Systems.

]]>Write an efficient algorithm that searches for a value in an `m x n`

matrix. This matrix has the following properties:

- Integers in each row are sorted from left to right.
- The first integer of each row is greater than the last integer of the previous row.

This is the first thing that comes to mind.

Traverse the matrix's each row and column value by value and get the number.

**Time Complexity: O$(n^2)$**

Why do I need to optimise, because the problem clearly says, write an efficient algorithm.

So, let's try to write an efficient algorithm.

What I can figure out is there's no way of traversing the array other than an outer for loop, that will traverse each row.

But what I can think of is using the first property of the matrix.

Integers in each row are sorted from left to right.

Since the array is sorted, I can use Binary Search to search for the value, and the complexity of this search binary search is O(logn)

**As of now the complexity of this solution stands at $O(n) + O(logn) = O(nlogn)$**

If I am thinking correctly, I can leverage the second point of the problem statement as well i.e.,

The first integer of each row is greater than the last integer of the previous row.

So, the idea is same, if the searched number is smaller than the current element than it's definitely in the previous collection.

So, I have to do binary search on columns as well, and complexity again becomes

$**O(logn)**$

So, adding row search with column search, we get

O$(logn)$ + O$(logn)$ = O$(logn)$

```
/**
* @param {number[][]} matrix
* @param {number} target
* @return {boolean}
*/
const binarySearchOnColumn = (matrix , target) => {
if(matrix.length === 1) {
return matrix;
}
const columnSize = matrix.length;
let midOfColumn = Math.floor(columnSize/2);
let slicedArray;
if(matrix[midOfColumn][0] > target ) {
slicedArray = matrix.slice(0 , midOfColumn);
} else {
slicedArray = matrix.slice(midOfColumn, matrix.length)
}
const finalMatrix = binarySearchOnColumn(slicedArray, target);
return finalMatrix;
}
const binarySearchOnRow = (workingArray,target)=>{
if (workingArray.length === 1) {
return workingArray[0] === target;
}
const rowSize = workingArray.length;
let midOfRow = Math.floor(rowSize / 2);
let sliceArray;
if (workingArray[midOfRow] > target) {
slicedArray = workingArray.slice(0, midOfRow);
} else {
slicedArray = workingArray.slice(midOfRow, workingArray.length)
}
return binarySearchOnRow(slicedArray, target);
}
var searchMatrix = function(matrix, target) {
const workingRow = binarySearchOnColumn(matrix , target);
const isElementFound = binarySearchOnRow(workingRow[0], target);
return isElementFound;
};
```

Results

If you find my thought process helpful, do tell me in the comments and don't forget to follow me on Twitter @sagars_01

]]>I have been interviewing a lot of folks in recent years, and I should tell you that the listed interview questions are not really frontend technology specific. These are for software engineers who are going to work in some cool products which serves customers at scale.

So, here are my favourite picks in no specific order with which I measure a candidate and also face a quite lot of time in my interviews.

Explain me "this" without using any JavaScript programming language reference, use a real world example.

Explain me event loop with a tiniest example.

Stock buy and sell problem : https://www.geeksforgeeks.org/stock-buy-sell/

Find duplicates in a string, optimise if you are traversing linearly.

Sorting domain names : https://stackoverflow.com/questions/342590/sorting-domain-names

Numeric keypad problem : https://www.geeksforgeeks.org/mobile-numeric-keypad-problem/

Coin change problem based on dynamic programming : https://www.geeksforgeeks.org/coin-change-dp-7/

Write tests of the previous question.

Design a schema for an order page in an e-commerce site.

Let's discuss about optimising a server rendered react application.

There are thousand of other great questions out there to prepare for an interview, but these are bare minimum that you can expect in a JavaScript interview. I am working for Lowes' where we are serving more than ~120M active users to buy and discover more than a million products. Working in these high performing tech companies, requires you to prepare holistically as a software engineer. Next post will be on system designs round.

If you want to know more on tech, product, interviews and JavaScript, follow me on twitter https://twitter.com/sagars_01

See you there.

]]>