Explanation of what

`onClickCapture`

is and how it differs from the`onClick`

propertyA brief overview of event propagation in the DOM

There are 3 phases in the lifecycle of an event in JavaScript

Capturing Phase

Target Phase

Bubbling Phase

This what it is looks like on a high level -

But for the scope of this post, we are interested in the **capturing phase.**

An event is in capturing phase when the event goes down to the target element.

As you can see from the above image the **Button** is the target element, so that event will start flowing from the top that is **HTML** till the Button.

`onClickCapture`

function fits into the capturing phaseIf you notice in the above image, I have declared a function `onClickCapture`

on **DIV** which is the **parent of Button**

So, as per the theory `**onClickCapture**`

should invoke a function (if any) associated with it while in the capturing phase.

That also means, `**onClickCapture`

** on **DIV will execute before** `onClick`

event of Button.

Here is a CodePen for you to demonstrate the event:

https://codepen.io/sagars_01/pen/oNMZKyY

`onClickCapture`

As front-end engineers most of the time, we tend to use reusable components and most of the time we dont have any control over the code of the component.

For example, at Lowes, we have huge teams which work across different products and we share React Components all the time.

*Situation*

Imagine yourself in a similar situation where youre using a button(B1) built by another team and B1 has an onClick method that has an event.stopPropagation(). Your use case is to trigger an API call from your codebase whenever the button(B1) has been clicked.

Note: event.stopPropagation() will stop the event from bubbling.

*Solution*

In this situation, you can use `onClickCapture`

on the parent div or tag of the button (B1) to achieve your result.

Example here in JSFiddle

https://jsfiddle.net/sagars71/hzev6um7/

The key takeaways for you are:

There are 3 phases of an event in JavaScript.

onClickCapture works on the Event Capturing Phase

onClickCapture can be used when you want to know if a child element has been clicked.

I encourage you to play with the JSFiddle and try to fit your use case on the same.

If you have learned something today, dont forget to share the post with your friends, colleagues and anyone who can benefit from this. This will motivate me to write more for you.

Do follow me on social, I post regularly on JavaScript, Software Engineering and Distributed System Designs. Twitter LinkedIn

]]>Software engineering is the process of designing, developing, and maintaining software systems. Software is everywhere, and you are using it to read this blog. A software engineer in some part of the world developed and built the software you are using.

The demand for skilled software engineers reflects the importance of software engineering. There will be a growing demand for professionals who can create, develop, and maintain high-quality software systems.

As the demands increase people have developed some myths about software engineering. I am Sagarmoy Sengupta, I am developing software since 2012. I am a Lead Engineer and my code helps one of the biggest retail brands in the world to serve 150M requests monthly. I will burst some of the common myths of software engineering in this blog post.

Anyone can be a programmer if they have these qualities:

**Dedicated**to learning.**Love to****Solve**problems.**Patient**and ready to find new ways in case things dont work.

99% of aspiring programmers quit at stage 1.

*Programming in general is like cycling, you get better at it over time and there are no shortcuts, no finish line*.

If you belong to non-technical background a guide or a mentor can help you. You can start following them over social media or just drop the

Writing well-organized code is important but it is not enough of its own. Without background or context, you won't understand the purpose of the code. So, it is very important to include these:

Documentation helps to make the code more transparent and maintainable. It provides context to other developers.

Proper Commit Message is important to have a clear record of what are the changes made, why are they made, and by whom.

Link to the task is important for the future developer to know the holistic view of the code in the business

This is the area that makes elite software engineers. Anyone can write code from scratch but it takes an expert to fix problems in an existing codebase.

This skill can't be learned by reading a book, a video, or a podcast. The skill of debugging comes from only two activities:

**Practice -**writing code year after year.**Experience -**in fixing bugs. I mean a lot of bugs.

If you want to read a great story on what makes a person an expert, head over to this famous story.

https://patrickthomson.tumblr.com/post/2499755681/the-best-debugging-story-ive-ever-heard

This statement used to be true some years back, but now with the introduction of AI, this is not true anymore. There's a diminishing line between a frontend engineer and a backend engineer or a mobile developer. The industry now works on Software Engineers who ship a product end to end.

We should consider large projects like cloud providers, space tech, etc. These projects are very hard and take a lot of specialists to develop. But this is a very small number of projects in the entire software world.

A specialist can do the work of 5 engineers, so it's best to hire a specialist early on in your project.

The downside of having too many developers on the team

Not everyone is going to get the best work.

A lot of time is spent on coordination and developers need to coordinate all the time.

Capacity is the most important stage while starting a project because if hired unmindfully the project deadline is going to decline.

It is best to hire Project Managers in this situation because they will have better experience in capacity planning.

This is the most controversial topic of them all.

**Computer Science is Mathematics.**

If you are good at maths it means you're good at problem-solving. Software engineering needs you to solve problems, that's the job.

You can quickly come up with solutions if you have a basic mathematical aptitude. It also doesn't mean you'd need Calculus or Discrete Mathematics on a day-to-day basis. Most of the time you'd solve simple quantitative problems.

Machine Learning, AI, and Data Science use Advanced Mathematical concepts. The foundation of advanced mathematical concepts is a huge advantage for you if you want to pursue these fields.

To sum up, having a solid foundation in Maths is beneficial to any programmer.

There are many other prevailing myths in the field of software engineering. I have explained the most common myths that I see or observe day to day.

Anyone can be a programmer

The code is self-explanatory

Debugging is easy

More developers are equal to faster development

You dont need maths to do software engineering.

I request every reader to stay informed and not believe all the Myths that they hear and always consult an expert whenever in doubt.

I wish to help all my readers and write about better software engineering, distributed systems, and interview preparation strategy.

If you liked it, do follow me on Twitter. It helps new writers like me.

]]>Coding challenges are a great way to enhance your coding skills and improve your problem-solving abilities. If you have a basic understanding of JavaScript, these challenges are suitable for you. If you don't have this foundation, consider completing a course like https://www.codecademy.com/catalog/language/javascript or finding a helpful playlist on YouTube.

So without further ado, lets dive right into some challenges:

Given any integer number, print all the numbers in reverse till 0.

**Example:**

```
// input = 10
// output = 10 , 9 , 8 , 7, 6, ... 0
function reverse(input) {
// Write your logic here;
}
```

To solve this problem youd need knowledge on **Loops**.

If you cant solve this right at this moment dont worry everyone has passed this stage. Now head to this link to learn about loops in JavaScript and try again.

Remember the physics lesson on temperature where we used a formula to convert Celsius to Fahrenheit? This problem is the exact representation of the formula in a program.

**Problem**:

Write a function that takes in a temperature in Celsius and returns the equivalent temperature in Fahrenheit.

**Examples**:

`convertToFahrenheit(0)`

should return`32`

`convertToFahrenheit(100)`

should return`212`

`convertToFahrenheit(37)`

should return`98.6`

**Constraints**:

The input temperature will be a positive integer or decimal in the range [-100, 100].

The output temperature should be rounded to the nearest hundredth.

**Notes**:

- The formula for converting Celsius to Fahrenheit is:
`F = C * 9/5 + 32`

Here you need knowledge on **Variables and Operators.** This will help you build your logical skills and put your mathematical skills to test.

#Hint1: If you need a refresher on variables and operation head to this link.

Write a function that takes in a string and returns the string with the characters in reverse order.

**Examples**:

`reverseString('hello')`

should return`'olleh'`

`reverseString('abcdefg')`

should return`'gfedcba'`

`reverseString('racecar')`

should return`'racecar'`

**Constraints**:

- The input string will only contain alphabetical characters and will have at most length 100.

**Notes**:

You should not use the built-in

`reverse()`

method for strings.Your function should be able to handle palindromes (strings that are the same forwards and backwards).

You can solve this challenge if you have paid some attention to the #1 challenge in this post.

**Hint: Read the string from the end and append to an empty string;**

If you need some refresher on properties and built in functions of strings, head to this post by w3schools

**Problem**:

Write a function that takes in two strings and determines if they are anagrams of each other. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

**Examples**:

`isAnagram('listen', 'silent')`

should return`true`

`isAnagram('hello', 'world')`

should return`false`

`isAnagram('anagram', 'nagaram')`

should return`true`

**Constraints**:

The input strings will only contain alphabetical characters and will have at most length 100.

The strings may not be case sensitive, so you should ignore the case of the characters when determining if they are anagrams.

**Notes**:

You should not use the built-in

`sort()`

method for strings.Your function should be able to handle anagrams that are palindromes (words that are the same forwards and backwards).

This is a tough one. So you better start thinking about how you can store or know if all the characters present in word1 is also present in word2.

Incase you are completely stuck start writing on paper or watch a video on YouTube.

Reference : https://www.youtube.com/watch?v=QZmh8-Auqo8

Write a function that takes in an array of numbers and returns the sum of all the numbers in the array.

**Examples**:

`sumArray([1, 2, 3])`

should return`6`

`sumArray([10, 20, 30, 40])`

should return`100`

`sumArray([-1, -2, 3])`

should return`0`

**Constraints**:

The input array will contain at most length 1000.

The numbers in the array may be positive, negative, or zero.

**Notes**:

- You should not use the built-in
`sum()`

method for arrays.

There are multiple ways to solve this, but the foundation of this challenge is store the data iterate through the array.

Heres the link to learn about iteration on array: https://www.w3schools.com/js/js_array_iteration.asp

These are the most beginner friendly challenges for you. Try to complete all of them without looking up the solution. Even if you are looking for the solution then do make notes about how did it work.

Consistency is the key to become a better programmer and no one has learned without practising daily. I wish you all the best.

If you liked what I post do follow me on Twitter. This will support and encourage me create more content like this.

See you next time.

]]>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.

]]>