With great pride let me introduce you to the best in class Database, & why you must be using this for every project going forward.
A while back I was dreaming of a project, that I thought had a lot of potential, and started scouring the internet, for the right technology, to make it happen.
I was new to System Design, so I just went blindly through the top of the list for every technology, to make the backend.
Turns out the technology at the top of the list may have been the best in the previous century, but in this century they feel like they could use a revamp.
Not just the tech stack itself, but how we talk to the backend. Everyone needs to get their hands on GraphQL to feel how revolutionary it is compared to what REST has to offer.
That brings us to Dgraph. I would go over each of the feature that will prove why:
Dgraph is truly a 21st Century Database!
See the official comparison by Dgraph: Dgraph compared to other Databases.
I didn't include a section for Dgraph vs other Graph database because it just wins out right against the biggest contender & Dgraph has a comprehensive comparison available. See: Dgraph vs Neo4j.

SQL Databases are chosen for ACID Properties, and relational nature.
But can't Graph DBs guarantee the same? What makes it so that only Relation Database are capable of those guarantees?
Dgraph meets all of the criterias a old school Relational Database does:
Dgraph outperforms Relational Databases in all frontier, and more. For instance it's Horizontally Scalable, even in free version, which famous RDBMS can't do out of the box!

The need for processing unstructured data, and the need for faster processing led to advent of NoSQL.
Startups are said to prefer NoSQL due to flexible schema, to allow future growth. Well Dgraph also has flexible schema, and lots more to benefit a startup!
Following features puts Dgraph at the upper echelon of Databases.
New Databases are cropping up, that introduce a layer on top of their Relational DB to allow GraphQL query, and all they end up doing is bloating up the stack by using Adapters that convert GraphQL to SQL or some other translations that introduce overhead.
Then there are services like Hasura, that generates the GraphQL API for existing database. But it comes nowhere close to how good a Native GraphQL solution gets.
GraphQL and Graph Databases are meant to play along, and having it as first class citizen of the Database makes it so much better. (Think Apple Hardware & Software.)
Just look how swift Dgraph can let someone make a Twitter Clone!

A distributed system has multiple components located on different machines that communicate and coordinate actions in order to appear as a single coherent system to the end-user.
That means, instead of having one big machine doing all the work, multiple smaller machines can divide the work among themselves.
Which allows a company like Google to scale to Googol!
Traditional RDBMS can't do that, you either move to a recently introduced RDBMs that introduced horizontal scaling or use a plugin, like you do with PostgreSQL. That is you would need Hyperscale (Citus)!
So why not go with a Database, that already beats other Databases in all aspects and is Distributed in nature out of the box!
Dgraph is also Jepsen Tested, so it is guaranteed that the Database meets all challenges of a Distributed System.

Graph databases are much faster than relational databases for connected data - a strength of the underlying model!
Graph Databases also make modelling and querying much more pleasant, meaning faster development. It's natural to think and draw in Graph shape than in tabular format.
Hence Graph Databases beat the traditional databases hands down, which puts Graph Databases way ahead of other DBs.
Then comes the Dgraph's competitors like Neo4j, which can't even hold candle to Dgraph's lightning performance!
For a comprehensive understanding, look at the benchmark done by Dgraph:


Geolocation has become an integral part of mobile applications, especially with the advent of smartphones in the last decade, the list of applications which revolves around users location to power application features has grown beyond imagination.
Real-world data is interconnected; they are not sparse; this is more relevant when it comes to location data. The natural representation of railway networks, maps, routes are graphs.
The good news is that Dgraph, the world’s most advanced graph database, comes with functionalities to efficiently store and perform useful queries on graphs containing location data. If you want to run queries like find me the hotels near Golden Gate Bridge, or find me all the tourist location around Golden Gate Park, Dgraph has your back.
Yet databases often lack this basic feature. For example if you use Postgres, you would need Postgis.


Graphs are more relational than the Relational DBs pretend to be.
The primary keys, the foreign keys and all that junk. It's like manually placing the wire on the mechanical board to patch in a call from one end to the other like in old days, when telephones first came to be.
Normalizing data is so much old school. Can we please move on, and just use a Data Structure that doesn't store data repeatedly and yet is able to retrieve data quickly!
So many issues can be avoided, if we just embrace higher dimensions. Instead of living like ants on 2d plane, let us soar through the space with Dgraph.
If Graph Database can handle a complex relational websites like social networks, then it can definitely handle every other kinds of relational data.

It's the easiest Database there is. No need to learn boring syntaxes, joins, normalizations.
Easy to learn, easy to set up, and most importantly easy to use!
Dgraph is Docker & Kubernetes native, so it plays along great. See: Dgraph Docker Images.
The ease with which you can define GraphQL Schema is mind blowing. You can use Interactive Schema builder or just plain text, and all the CRUD APIs get generated by Dgraph!
Dgraph allows us update the schema whenever we desire, and the Graph updates accordingly.
You can use Swagger Editor to generate Server stubs REST APIs, with OpenAPI specification, but that doesn't even scratch the surface of what Dgraph does.
To top it all, Dgraph even has Slash GraphQL, it's hosted managed Dgraph service. And if that doesn't say easy, I don't know what does!


Search functionality is a must in a Database, having it built in and not having to create a separate Datastore for search functionality is just a blessing.
Dgraph uses indexes to make search efficient.
int, float, geo and date have default indexes, but string has options of what index types to choose. Multiple indexes can be built for the same string valued predicate.
term for use with allofterms and anyofterms. (default)exact for use with inequality - matching whole string.hash as for exact but hashes string - useful with long strings.fulltext for full text search with alloftext and anyoftext.trigram for use with regular expressions.Full text search is what Google does for web pages. It’s different to term matching because it tries to respect language, grammar and tense. For example, matching search term run with documents containing run, running and ran.
It doesn’t match terms exactly and instead makes use of


Dgraph GraphQL comes with built-in authorization. It allows you to annotate your schema with rules that determine who can access or mutate the data.
There are two important concepts in auth:
Dgraph does it amicably, and plays nicely with Apollo GraphQL.


If generated CRUD API falls short of your requirement, i.e. Factory made superbike doesn't float your boat, then you can add custom business logic using JS Lambda Functions
Dgraph Lambda is a serverless platform for running JavaScript on Dgraph and Slash GraphQL.


Encryption is a process that encodes a message or file so that it can be only be read by certain people.
Dgraph has something called Encryption at rest, which refers to the encryption of data that is stored physically in any digital form. It ensures that sensitive data on disks is not readable by any user or application without a valid key that is required for decryption.
Dgraph provides encryption at rest as an enterprise feature. If encryption is enabled, Dgraph uses Advanced Encryption Standard (AES) algorithm to encrypt the data and secure it.
Compression is the method computers use to make files smaller.
Dgraph saves storage space by compressing every block of data using one of the two compression algorithms provided:

Hope I have shed enough light to convince you to opt for Dgraph.
If you are stuck with other Databases, use Live Loader & Bulk Loader to port the data into Dgraph. Else if you are starting from scratch then definitely go for Slash GraphQL, the official managed offering from Dgraph Labs. See Pricing:

YSK: Most System Design Interview questions can be answered with Dgraph!
The community behind Dgraph is massive, and so is the company.

Let me know your thoughts down in the comments below.
]]>Svelte is probably the best front end framework till date, given how little mess it leaves in the runtime and how little boilerplate it adds in author time.
It's simple just like Handlebars (albeit without 2 curly braces), yet powerful. It takes Handlebars further, by facilitating updates of the DOM, event-handling, frontend-backend communication and much much more.
Frameworks are not tools for organizing your code, they are tools for organizing your mind. - Rich Harris
Here's a list of all the reason front end development should happen using Svelte.
React is not fully reactive
— Dan Abramov (@dan_abramov)
Instead of using techniques like virtual DOM diffing, Svelte writes code that surgically updates the DOM when the state of your app changes.
It uses a labelled statement (aka Destiny Operator), to facilitate change detection. So:

Virtual DOM is slow, and even the react team knows that.
That's why they have given us, Abstraction Leaks, to tell the dumb framework not to update somethings:
shouldComponentUpdateReact.pureComponentuseMemouseCallbackIn Svelte however, change detection is much more precise as the compiler knows what to update when something changes, thanks to its advanced Reactive nature.
So no overhead like a Virtual DOM is even remotely necessary.

React apps are 40% larger compared to Svelte app, due to boilerplate code. If you have worked with React, you can relate.
I have to make changes to 6+ files to get something done, and that doesn't say how many lines of code I have to repeat. (DRY Principle is thrown out the window.)
Svelte overcomes that by:
Compilers are the new frameworks.https://t.co/BcAQeoIdcL
— Tom Dale (@tomdale)
Unlike React, Vue or Angular, that do the bulk of their work in the browser at runtime. Svelte is a compile time framework.
A framework should be thing, that runs in your build step.
It shifts that work into a compile step, taking our high level declarative components and turning them into efficient, imperative, low level code to manipulate the DOM directly.
All these results in a framework free vanilla js code at runtime.
The implications are:

CSS is component scoped, which saves a lot of headache, Styling won't leak outside a component or leak into one.
Unnecessary styles gets purged by the compiler, so no more forgetting to remove unused CSS.
It's even easy to change style, classes programmatically without even using a CSS in JS library.

AWS bills will be lower, as Svelte doesn't need to create a component tree & then serialize it. It just outputs a string.
Sapper takes the component framework and makes it an Application framework and adds:


Unlike other frameworks, where animations are an afterthought, and not really part of the library. Svelte believes it to be core of the user's experience.
There's libraries like GSAP, to achieve animations, but is it too much to ask for something built in with the framework that doesn't add a lot of weight to the website.
Svelte compiler converts javascript based animation to optimized CSS animations. Which means:
See:


Not all application state belongs inside your application component hierarchy. Sometimes, you'll have values that need to be accessed by multiple unrelated components, or by a regular JavaScript module.
There are as many state manager, as there are frameworks. (Redux.js, Effector.js, ...)
But the built in state manger is just sublime.


If the points mentioned above, doesn't speak volumes about how revolutionary this Framework is, maybe a demonstration will.
See: - How Svelte beats react without gimmicks like Async or Debounce.


It just works with RxJS out of the box. So:
Observer Pattern, the Iterator Pattern, and Functional Programming.
Svelte is quite literally the Tesla of Front end frameworks!
However, you can take it to the next level with: Micro-Frontend

Let me know your thoughts down below.
]]>A browser based game, driven by A Star path finding algorithm, and made using Angular 2.
The code is deprecated, but feel free to look around the git repo. It was made back in 2018, to showcase what I'm capable of and:
As a tribute to shitty people that made my life a living hell at my first job!

You can either play it here in this page itself, or else visit Don't Let Him Poo website!
Tap around to figure out the controls.
I optimized the site for mobile & desktop. The design resembles a calendar, has dark mode by default.
It has a modified Material Design, as I used paper cutouts!


Although the code has been deprecated, I merely want to have it present in my Blog as a reminder of what I have overcome.

Back at Cognizant I was experiencing burnout from overwork, so I got the inspiration to make this game.
I was forced to work for 16 hours on average, maxing out at 19 hours 30 minutes. I had to go on Saturday 11 in the morning and return 5:30 AM on Sunday next day. (My morning bowel movements were being interrupted 😅)
Therefore I chose Calendar like design for the game view as it depicts the excruciating mental pain that lasted for my entire stay at Cognizant.
I was neither given compensatory off, nor payment for overtime & weekends. It was demeaning, and inhumane working at Cognizant under those managers.
Employees join companies but leave managers.
All I got out of my ordeal at Cognizant, is a searing back ache, occasional pizza, and this game. The gameplay reflects what I went through.
You play as a manager of a dysfunctional organization and you have to manage your underling in such a way that you don't let him poo. Keep him busy, make him work, get paid. And then use money or pizzas to keep him too occupied to notice.
The game is not fun, it's a casual depiction of my ordeal, and technical wizardry.
You will always win, playing the game as a manager, as the game is rigged against the employee. (Similar to how it is in Real Life)
Let me know your thoughts down in the comments below.
]]>It's high time we break the monolith architecture in the front-end, the way it's broken in the back-end: stateless, componentized, tech-agnostic & separate!
Websites today are still made the same way they were 20 years ago, with a cumbersome monolithic approach to building sites, storing data, and delivering content. It’s time for a new way to build the web. - GatsbyJS’s Founder Kyle Mathews
After experiencing development using React & Angular, I have nothing but pure loathing for the current state of front-end web development.
Especially with the Agile and it's weekly delivery mandate, the monolithic approach to front-end development is just a huge pain in the tushy. Requirements changes at the whim of the project manager, or at the last minute, due to misunderstood use case.
Front-end, a monolith, however remains inflexible unlike the micro-service based back-end.
While developing a back-end we strive to make it as stateless as possible, why not for the front-end. Why have a shared state at all, only to have it get unmanageable in the long run? What is a shared state, if not a glorified Global variable?
Then comes along the frameworks and their countless dependencies, verbosity, and hand holding opinions.
Sure there's Storybook.js for those frameworks, to allow development of component in isolation, but the result still remains a monolith.
Defacto front-end frameworks, like React, Angular & Vue.js, aren't even fast enough. On top of that they bloat the site with JavaScript. See: A RealWorld Comparison of Front-End Frameworks with Benchmarks.
Svelte already beats the Monoliths in their own game, however we can take it even further with Micro-Frontend approach.
This post is about taking the front-end to the next level. Breaking the site and building the individual pieces the way back-end development is done.
The following tools are what can help you with Micro-Frontend development. Both of the tools, when combined together, can make one master of webdev.
Bit is an open-source cli tool for collaborating on isolated components across projects and repositories.
Instead of building the whole project in one build process, the component-driven CI from Bit.dev splits the build process so that it only runs on the components that actually changed, and propagates the changes, to build every impacted component, on every page, in every app.
So instead of messing with cumbersome iframes or finding alternative solutions, we can rely on build-time integrations that do not couple release processes together.
Since components are decoupled, we can easily add, replace, hotfix, or even rollback a single component or feature.
On top of that, features such as visual component documentation, a smart component search, and even live simulations all help to make all the components discoverable so that we don’t have to maintain any additional documentation websites, registries or tools.
See: How We Build Micro Frontends blog post by Bit.dev.


Storybook is an open source tool for developing UI components in isolation. It makes building stunning UIs organized and efficient.
Checkout how Airbnb react date picker Storybook is organized.
It helps with documentation, mocking hard to reproduce use case, build in isolation, and do visual testing on components.
However Storybook solves half of the equation.
Storybook excels in the visual development of standalone components locally, Bit handles the full lifecycle of components already created. It completes Storybook from the point a component lives in your project, and beyond.
See: How is bit.dev different from Storybook? blog by Bit.dev.

There needs to be an overarching framework to glue different components together. And I feel the following frameworks to be the best.
Handlebars is a simple templating language. It uses a template and an input object to generate HTML or other text formats. Handlebars templates look like regular text with embedded Handlebars expressions.
It's great for readonly content, for instance this blog is made using Handlebars. Try turning off the javascript, and the site will still work as the template have been rendered in the server.
However it's not good for fast (incremental) updates of the DOM, event-handling, frontend-backend communication. - See: When not to use Handlebars?
As for when to use it, checkout Jamstack.

Svelte takes Handlebars further, by facilitating updates of the DOM, event-handling, frontend-backend communication.
It’s actually not a framework but a compiler with a templating language like Handlebars.js! (i.e. with single curly braces instead of double)
Svelte being a compiler and templating language is what makes it so powerful.



Sure, lots of JS libraries come out every minute. Not every one of them is worthy of our attention.
However Svelte does something no other framework does, and that deserves everyone's attention. Combine that with Micro-Frontend architecture, and we are golden.
What do you think, let me know in the comments below.
]]>System design interviews are open ended, with no answer that's 100% effective. All we have to do is weigh options and put forth the best one forward.
Here are some of the aspects to keep in mind while designing your next large scale system.
Monoliths used to be the way of life. A single system capable of doing everything.
Breaking the responsibilities into bite sized micro services is the best way to scale up systems. Those services can be individually updated, can scale independently, can use different tech than others.
It brings lots of other challenges however, such as distributed consensus issue, fault tolerant design issue, health check, service discovery, monitoring, etc.
The following checklist should tell you just how much the landscape has changed, compared to what is being taught in colleges.

Vertical scaling is merely adding more and more to the spec of an existing system. That however is unsustainable at scale.
Horizontally scaling the system is the best way forward if Google's scale is desired. However dividing the system into smaller pieces has challenges of its own.
Scaling vertically up is great when starting out. As apparently engineers are costlier than SSDs and Ram. Which is why Plenty of Fish's Architecture uses the scale up approach and same goes for Stack Overflow's Architecture!
Load balancing is the efficient distribution of network or application traffic across multiple servers in a server farm. Each load balancer sits between client devices and back-end servers, receiving and then distributing incoming requests to any available server capable of fulfilling them.
Some of the best ones are - Nginx, Envoy Proxy.

A Web API is an application programming interface for either a web server or a web browser.
There are several protocols in the stack making it possible for clients & servers to communicate with each other.
HTTP is the underlying communication protocol of the World Wide Web. HTTP functions as a request-response protocol in the client-server computing model.
It's a one way communication protocol, which means when we send a request we get a response. But server can't send something out of its own volition as the connection is one way.
It's best for passive applications that doesn't need to be updated live.
Few architectural patterns based on HTTP are REST, GraphQL. They are topics for another post.

It's a bi-directional protocol, that supports full-duplex communication - client and server can talk to each other independently at the same time.
It uses Single TCP connection so client and server communicate over that same TCP connection throughout the life-cycle of Web Socket connection. Which means less overhead with handshakes happening again and again.
This is best for real time applications, or real time part of the application.

In what format the messages are passed between sender and receiver is also one decision that needs to be made.
Binary formats like MessagePack, Protobuf are naturally compact, yet front end can't understand them. They are great for server to server communications.
Text format like JSON is not small in size, however it's natural to JavaScript, hence great for front end applications and can be compressed to match the size of Protobuf or MessagePack.
The trade-offs need to be analysed, as it's done below.

Depending on the type of data being stored and requirements, several types of storage exist.
A database is a collection of information that is organised so that it can be easily accessed, managed and updated.
Several DB types exists with varieties of query languages to talk to them. Like Relational, No SQL, Graph DB, Key Value, Time Series, etc.
They all have something to offer, with their own advantage & disadvantages which is a topic for another day.

Object stores are best suited for blobs like images & videos. As they can't be stored in Databases.
Object storage is a computer data storage architecture that manages data as objects, as opposed to other storage architectures like file systems which manages data as a file hierarchy, and block storage which manages data as blocks within sectors and tracks.
The main advantage of using object storage are metadata tags, which allow for much better identification and classification. Search capabilities and unlimited scaling make object storage ideal for unstructured data.

It's an essential component of large scale systems.
Caching is a technique that stores a copy of a given resource and serves it back when requested. When a web cache has a requested resource in its store, it intercepts the request and returns its copy instead of re-downloading from the originating server.
It's the same principle behind Dynamic Programming. i.e. Instead of computing something again and again or retrieving something from slower media, why not cache the data in a faster storage and serve from there instead.
Redis is one such tool. It's an in-memory data store, which is used as a distributed, in-memory key–value database, cache and message broker.
Cache can be sped up further with compression. See: Doordash's LZ4 Study.

A CDN (Content Delivery Network) is a highly-distributed platform of servers that helps minimise delays in loading web page content by reducing the physical distance between the server and the user. This helps users around the world view the same high-quality content without slow loading times.
They do so by serving the intended content from closest data centre.

Some compression algorithms are best used passively like Brotli, or media compression algorithms like MP4.
Netflix has to support lots of devices of varying calibre. Each device has a video format that looks best on that particular device.
Netflix also creates files optimised for different network speeds. If you’re watching on a fast network, you’ll see higher quality video than you would if you’re watching over a slow network.
Stranger Things season 2 has 9,570 different video, audio, and text files!
Excerpt from: Netflix - What Happens When You Press Play?
All of that compression is done passively once, instead of on the fly.
This kinds of decisions need to be taken in requirement gathering phase.

Then there's active compression for text like data, in transit or for storage in memory.
The algorithm needs to be fast in both compression & decompression stage and eat up less CPU while doing so.
Some interesting reads:


The Byzantine Generals Problem is a term used in computing to denote a situation wherein certain components of a system may fail if participants don't agree on a 'concerted strategy' to deal with the problem.
The Byzantine Generals' Problem is the analogy most often used to illustrate the requirement for consensus for distributed systems. i.e. How do you make sure that multiple entities, which are separated by distance, are in absolute full agreement before an action is taken?
I ran into this problem when I designed a Distributed Socket Server. Multiple instances of the same server were disagreeing with each other under load, i.e. they had conflicting data in them.
Eventually I found out about Redlock algorithm algorithm and then used it to achieve distributed consensus.
Raft Consensus Algorithm is the best I found so far, it's used by Dgraph for their distributed graph database!

Put everything into a queue. Votes, comments, thumbnail creation, precomputed queries, spam processing and corrections.
Excerpt from Reddit - Lessons Learned From Mistakes Made Scaling To 1 Billion Pageviews A Month.
Queues allow you to know when there’s a problem by monitoring queue lengths. Side benefit is queues hide problems from users because things like vote requests are in the queue and if they aren’t applied immediately nobody notices.
It's a clever little trick, often used in single page applications called Optimistic UI. It's a pattern that you can use to simulate the results of a mutation and update the UI even before receiving a response from the server!
So when user clicks on up-vote, instead of showing a loader or loading the whole page, we immediately show the effect of the button press. Meanwhile the user's button press is sent to a message queue which will be processed asynchronously by the server.
There are several message queues, Rabbit MQ, Kafka, NATS.

If this post doesn't help you crack an interview, perhaps it can help you understand how you should approach your next big project.
Learn from the mistakes of others. You can't live long enough to make them all yourself. - Eleanor Roosevelt
A site called High Scalability has some of the best articles on System Design.
Like the following postmortem!

What do you think? Let me know your thoughts down in the comments below.
]]>There's tons of Sorting Algorithms, however for interviews, being able to implement a select few and explain their time complexity should be enough.
Also check the sorting algorithms used by different languages, to see what they use.
For JavaScript, Mozilla uses Merge Sort, but Chrome uses Quick Sort and Insertion Sort (for smaller arrays).
Quick Sort is a Divide and Conquer algorithm. It picks an element as pivot and partitions the given array around the picked pivot. There are many different versions of Quick Sort that pick pivot in different ways. (e.g. First, Last, Random, or Median Element as pivot)
Keep following aspects in mind while choosing Quick Sort.
function partition(arr, start = 0, end = arr.length - 1) {
// Let's choose the pivot to be the arr[start] element
let pivot = arr[start];
let swapIdx = start;
for (let i = start + 1; i <= end; i++) {
if (arr[i] < pivot) {
swapIdx++;
// Swap current element with the element at the new
// pivot index
[arr[i], arr[swapIdx]] = [arr[swapIdx], arr[i]];
}
}
// Swap the pivot element with the element at the pivot index
[arr[swapIdx], arr[start]] = [arr[start], arr[swapIdx]];
// Return the index of the pivot element after swapping
return swapIdx;
}
// Recursive
function quickSort(arr, left = 0, right = arr.length - 1) {
// Base case is that the left and right pointers don't overlap,
// after which we'll be left with an array of 1 item
if (left < right) {
let pivotIndex = partition(arr, left, right);
// For left subarray, which is everything to the left
// of the pivot element
quickSort(arr, left, pivotIndex - 1);
// For the right sub array, which is everything to the
// right of the pivot element
quickSort(arr, pivotIndex + 1, right);
}
// Return the array, when it's of length 1 i.e, left === right
return arr;
}
Merge Sort is a Divide and Conquer algorithm. It divides the input array into two halves, calls itself for the two halves, and then merges the two sorted halves.
Keep following aspects in mind while choosing Merge Sort.
function merge(arr1, arr2) {
// Make a new array, and 2 pointers to keep track of elements of
// arr1 and arr2
let res = [],
i = 0,
j = 0;
// Loop until either arr1 or arr2 becomes empty
while (i < arr1.length && j < arr2.length) {
// If the current element of arr1 is lesser than that of
// arr2, push arr1[i] and increment i
if (arr1[i] < arr2[j]) {
res.push(arr1[i]);
i++;
} else {
res.push(arr2[j]);
j++;
}
}
// Add the rest of the remining subarray, to our new array
while (i < arr1.length) {
res.push(arr1[i]);
i++;
}
while (j < arr2.length) {
res.push(arr2[j]);
j++;
}
return res;
}
// Recursive merge sort
function mergeSort(arr) {
// Base case
if (arr.length <= 1) return arr;
// Splitting into two halves
let mid = Math.floor(arr.length / 2);
let left = mergeSort(arr.slice(0, mid));
let right = mergeSort(arr.slice(mid));
// merging the two sorted halves
return merge(left, right);
}
Insertion sort works similar to the way you sort playing cards in your hands. The array is virtually split into a sorted and an unsorted part. Values from the unsorted part are picked and placed at the correct position in the sorted part.
function insertionSort(arr) {
for (let i = 1; i < arr.length; i++) {
// Start comparing current element with every element before it
for (let j = i - 1; j > -1; j--) {
// Swap elements as required
if (arr[j + 1] < arr[j]) {
[arr[j + 1], arr[j]] = [arr[j], arr[j + 1]];
}
}
}
return arr;
}
Heap Sort is a comparison based sorting technique based on Max Heap. We first place the maximum element at the root and then poll repeatedly till heap is empty.
// Create Max Heap
function maxHeap(arr, i) {
const left = 2 * i + 1;
const right = 2 * i + 2;
let max = i;
if (left < arrLength && arr[left] > arr[max]) {
max = left;
}
if (right < arrLength && arr[right] > arr[max]) {
max = right;
}
if (max != i) {
swap(arr, i, max);
maxHeap(arr, max);
}
}
function swap(arr, i, j) {
const temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
function heapSort(arr) {
arrLength = arr.length;
for (let i = Math.floor(arrLength / 2); i >= 0; i -= 1) {
maxHeap(arr, i);
}
for (i = arr.length - 1; i > 0; i--) {
swap(arr, 0, i);
arrLength--;
maxHeap(arr, 0);
}
return arr;
}
Bubble Sort works by repeatedly swapping the adjacent elements if they are in wrong order.
function bubbleSort(arr) {
let noSwaps;
for (let i = arr.length; i > 0; i--) {
noSwaps = true;
for (let j = 0; j < i - 1; j++) {
if (arr[j + 1] < arr[j]) {
// Swap
[arr[j + 1], arr[j]] = [arr[j], arr[j + 1]];
// Make 'noSwaps' false
noSwaps = false;
}
}
// End the iterations if there were no swaps made in one full pass
if (noSwaps) {
break;
}
}
return arr;
}
It's terrible, just explaining that should be enough.

Choice of Sorting algorithm in an interview is done based on time space trade-offs among other factors.
| Algorithm | Time Complexity | Space Complexity | ||
|---|---|---|---|---|
| Best | Average | Worst | Worst | |
| Quick Sort | Ω(n log(n)) | Θ(n log(n)) | O(n^2) | O(log(n)) |
| Merge Sort | Ω(n log(n)) | Θ(n log(n)) | O(n log(n)) | O(n) |
| Heap Sort | Ω(n log(n)) | Θ(n log(n)) | O(n log(n)) | O(1) |
| Bubble Sort | Ω(n) | Θ(n^2) | O(n^2) | O(1) |
| Insertion Sort | Ω(n) | Θ(n^2) | O(n^2) | O(1) |


In real world, variations of above sorting algorithms are used.
For example Python uses an algorithm called Tim Sort which is a hybrid sorting algorithm, derived from Merge Sort and Insertion Sort, designed to perform well on many kinds of real-world data.
| Algorithm | Time Complexity | Space Complexity | ||
|---|---|---|---|---|
| Best | Average | Worst | Worst | |
| Tim Sort | Ω(n) | Θ(n log(n)) | O(n log(n)) | O(n) |
Hope the above resources helped you. Please let me know your thoughts down below.
]]>Lets begin with the basic data structure, in the data structure line up.
An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. This makes it easier to calculate the position of each element by simply adding an offset to a base value.
const arr = [1, 2, 3];
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
// Output:
// 1
// 2
// 3
It starts out simple, however this data structure is very versatile and can be used to solve lots of problems.
Arrays and its related Data Structures & Algorithms are used to solve a lot of problems.
All the Data Structures mentioned below, use Array underneath in one way or another.
There's difference between sorted & unsorted array, in terms of time complexity and problem approaches.
For instance, search becomes faster in a sorted array, but insertion gets slower.


String is like an Array of characters, and all of the Array sub problems / approaches can be applied to it as well.
However it adds lot more variations. Like Sub-string, Palindrome, Regular Expression, ...
const str = "Hello, World";
console.log([...str]);
// ["H", "e", "l", "l", "o", ",", " ", "W", "o", "r", "l", "d"]
// or
console.log(str.split(''));
// ["H", "e", "l", "l", "o", ",", " ", "W", "o", "r", "l", "d"]Array of arrays is called a matrix.
It can be any number of dimensions. However the common one is a 2D matrix.
It has Pixel Grid, Shortest Path, Graph, Island style problems.
const twoDArr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
console.log(twoDArr); // [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
It's a complete binary tree, stored in an array. It has few formulas you need to remember and then you are golden.
Variations include: Min heap, Max heap.
In an interview, we don't have to write the whole thing. Instead we can just pretend we already have the data structure ready, as a separate function.
import heapq
li = [5, 7, 9, 1, 3]
heapq.heapify(li)
print(li) // [1, 3, 9, 7, 5]
heapq.heappush(li, 4)
print(li) // [1, 3, 4, 7, 5, 9]It's is a data structure which stores data in an associative manner i.e. in an array format, where each data value has its own unique index value. Access of data becomes very fast if we know the index of the desired data.
We don't need to know how to implement a Hash Table from scratch to be able to use it.
const hashMap = {
'hello': 'world',
'hakuna': 'matata',
};
console.log(hashMap['hakuna']); // 'matata'Stack follows LIFO, while Queue follows FIFO.
We can either use array for stack & queue implementation, or a linked list. Later being the better approach if random access is not required.
const stack = [1, 2, 3];
stack.push(4); // Push at the end of the array
stack.pop(4); // Pop from the end
console.log(stack); // [1, 2, 3]
const queue = [2, 3, 4];
queue.unshift(1); // Enqueue at the beginning of the array
queue.pop(); // Dequeue at the end
console.log(queue); // [1, 2, 3]All the Algorithms mentioned below use Array one way or other.
It's an efficient search mechanism that is done on a sorted array. It takes Log n time, instead of linear time to search through the array.
It is similar to a dictionary search humans perform.
var search = function(nums, target) {
let low = 0, high = nums.length - 1;
while(low <= high) {
mid = parseInt((low + high) / 2);
if(nums[mid] == target) {
return mid;
} else if(target > nums[mid]) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
};It's a small category compared to the rest of the line up, however it's worth a mention.
Problems include: Longest Sub-string, Consecutive 1s, ...
This approach will open up doors for solving few tricky problems.
Like: Linked List Cycle, String Reversal, ...
A Sorting Algorithm is used to rearrange a given array or list elements according to a comparison operator on the elements.
const arr = [5, 4, 3, 2, 1];
console.log(arr.sort((a, b) => a - b)); // [1, 2, 3, 4, 5]A greedy algorithm is a simple, intuitive algorithm that is used in optimisation problems. The algorithm makes the optimal choice at each step as it attempts to find the overall optimal way to solve the entire problem.
Dynamic Programming is mainly an optimisation over plain recursion. The idea is to simply store the results of sub-problems, so that we do not have to re-compute them when needed later.
This is the biggest and toughest category of them all.
We shall conquer this category eventually.
This was just an introduction to the vast category that is Arrays. I will eventually write about each of the above categories.
Let me know your thoughts below.
]]>While I was just beginning my preparation, I came across this:
Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off.
— Max Howell (@mxcl)
It maybe sarcastic, but big companies still choose to interview using this method and there's no way around it if we want to get in!
The quote scared me a bit as I am not the one who wrote Homebrew! I was merely starting out.
So only way to get over that fear, I feel this question to be the first one I should write about.


A simple preorder traversal is the best way forward.
While visiting the root node, we swap the left & right child and then visit the left & right child respectively.
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
var invertTree = function(root) {
// Recursion must have a base condition.
if(root == null) {
return root;
}
// A simple swap of let & right nodes of a root.
let tmp = root.right;
root.right = root.left;
root.left = tmp;
// Recurse on both sides in Preorder Traversal.
invertTree(root.left);
invertTree(root.right);
return root;
};Implement the preorder traversal in iterative manner.
While visiting the root node, we swap the left & right child and then visit the left & right child respectively.
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
var invertTree = function(root) {
if(root == null) {
return root;
}
let stack = [root], node, tmp;
// Use stack as this problem is a variant of Depth First Traversal
while(stack.length) {
node = stack.pop();
if(node == null) {
continue;
}
// Simple swap of left & right node
tmp = node.right;
node.right = node.left;
node.left = tmp;
stack.push(node.left);
stack.push(node.right);
}
return root;
};It's one of the most easy problem, that doesn't seem easy till you do it yourself.
What did you think? let me know down below.
]]>In a previous post, I put forth 15 reasons FAANG companies are worth the effort of prepping for interview. It would be unfair if I don't post how we can make it happen!
A little disclaimer before we begin. I have yet to get an interview for any of the Big Four. I'm a fellow aspirant such as yourself, but having prepped for it several times I'm a bit used to the process.
Several resources exist and I'm going to lay them out in an organised fashion for your kind perusal.

Use whatever you already know.
However, you have to bear in mind that:
So keeping the above points in mind, I would suggest you to choose a simpler language. Perhaps dynamically typed, interpreted one, with lots of inbuilt data structures.
You can't go wrong picking up Python, or JavaScript for the coding interview.
A pseudo-code like language, best suited for interviews.

Best choice, if you already have a background in web development.

Don't get lost in the sea of products, websites, books. Rather settle for the following list of resources, as they are more than enough to get you where you want to go.
I would recommend getting a book to orient yourself, followed by lots of practice in an online judging portal, followed by YouTube to help you when you get stuck.




Just reading code isn't going to make you a great coder. You have to practice as well.
And best way to practice and get validated for your approach is to write code in an online portal.
There are several online judges, like Topcoder, Codechef, HackerRank, SPOJ.
However best of the best is LeetCode. So don't you waste your time trying to find the best one of the lot, as I have already done the research on your behalf.
LeetCode's is the best because of:


Apart from remembering the common ones, you have to learn to analyse the complexity of the code you are writing.
Cracking the Coding Interview has a chapter explaining Big O in great detail.


Data Structure is the approach of storing data so as to make it easy to operate on. Each structure has their advantage, which is a topic for another day.
There's tons of data structure, but the ones interviewers are looking for are as follows:

Algorithms are operations performed on data structures, to come up with the solution to problems.
There's countless algorithms in the wild. However Coding Interviews rarely include those. So it's better to focus on the limited category presented below:



Candidates with 4+ years experience will be questioned on Low Level & High Level design in their interview.
System Design is not an exact science, hence you aren't expected to make the best design from the get go. Rather your approach and flexibility is monitored in these rounds.
HighScalability is a great place to see how other big companies approach their system design problems.
Then there's YouTube.

In the book, Cracking the Coding Interview, you will find a precise guide to prepare for the behavioural interview. See: Cracking the Soft Skills.pdf
You must prepare for each company you are about to interview for, as the expectations are different based on the culture the company portrays.
For example Amazon expects candidates to answer each of the questions, justifying the Leadership Principles.


Application Tracking System is the modern gatekeeper, stopping our resume's from ever getting noticed by a real person. So prepare your resume with that in mind.
Soon I'll be adding a guide to make the best of the best resume.

Forget applying on the online portal, as your applications will go unnoticed.
Your best bet, after having spent months on prepping for the coding interview, is to get a referral from someone who works for the company.
Starting is the most difficult part of the process, followed by discipline & perseverance to continue down this path. So start your journey today.
What do you think? Let me know your thoughts down below, and subscribe if you want to be updated as and when I post guide on some of the steps mentioned above!
Good luck with your future endeavour.
]]>After spending a few days, testing out lots of date pickers, I have found FlatPickr to be the best date picker so far. Here's Why:
See: Examples
FlatPickr has 8 themes, all separated into different CSS Files that can be imported.
See: Themes.
FlatPickr can be localized locally or globally.
See: Localization.
FlatPickr supports plugins, like Confirm Date, Week Selection, Range, etc.
See: Plugins.
When FlatPickr detects a mobile browser, it turns the date input into a native date/time/datetime input.
Native datetime selection provides a UX that’s familiar to the user and is superior to most web-based solutions.
See: Mobile Support.
The API is straightforward, UI is beautiful, and UX just rocks. If those don't make it the best of the best, I don't know what does!
Let me know what you think, below.
]]>Interviewing at FAANG is daunting, heck even getting an interview at one of them is difficult, and downright unfair. But getting into one is worth it!
FAANG is an acronym for Facebook, Amazon, Apple, Netlifx, Google.
Sure you may not like what Facebook stands for, or Amazon's for that matter. But that's a topic for another day.
However that's not the reason I'm writing this post.
I'm merely reiterating some of the reasons you already know, but you need to be constantly reminded, to keep true to your goals.
Also this list is entirely from an outsider's perspective, I may get lucky enough for an interview someday and then after joining I might have the privilege to write why you shouldn't get into one!

FAANG engineers are some of the smartest people in the world, and that's a fact. Imagine getting in one, you immediately get certified as the best of the best.
Bye bye impostor syndrome, as working in one of those is a huge confidence booster. As body building does to your body, getting into a top tier institution does the same to your brain.
Imaging sitting in a bar and name dropping working at any of the FAANG, the kind of attention you get from people is phenomenal.

Huge parties, paid leaves, health insurance to name a few. Checkout their respective sites for all the details.

All you can eat food.
People born with silver spoon in their mouth or people with spouse that cooks may not realise this, but having this option is just tremendous.
We don't have to shell out large portion of our earnings to eating, nor do we have to rack our brain to figure out where to eat. (One less decision to fatigue us!)

A substantial salary is a must.
If you earn 1/10th of the FAANG salary, you will be able to save or invest 1/10th the amount. Thereby postponing your early retirements plan.
Not just saving or investment, being able to afford a house, being able to ride whatever you want is also a huge plus point.
Imagine not needing to use your credit card to purchase something you desire.

Stock options sweetens the deal even further.
There's no better way to feel invested, than to get stocks when you join a company. The more the better.
And if you have seen the graph of stock prices of FAANG companies, you know what you will be getting in the long run!

Outing to foreign countries!
I was surprised to learn that once a year, a outing to different country is part of the deal.
Imagine not going to your local resort for a change, and visiting an entirely different country!

Ex FAANG engineers have a demand unlike anything.
It's a resume seller. Perhaps ATS systems are tuned to check if an applicant is ex Google or ex Facebook engineer!
It's like graduating from a Ivy League college!

Nerd out with others that have the same passion as you. I always hoped to find people that are geeks like me from college days.
Not only you get to share what you learnt, you also get to learn from others experience.
You don't get that in a small company, where all your colleagues can think about or do is go home, go to a bar, go to movies...
I understand work life balance is a thing, but if people don't even bother to better themselves in their free time then what's the point?

Having an idea is well and good, but execution matters even more.
You might know the pain of mentioning an idea to your peers, for your peers to say no, only to see someone else make it happen!
Since the people you are working with will be of same calibre as you, there's a high chance that you will be able to execute your dream together.

Ever had that one annoying guy from HR, constantly pester you to wear clothes different from what you are comfortable in?
I have, and it always strikes a nerve.
If wearing casual makes me feel comfortable and I can perform better, what's the point of wearing business attire the whole time?
Instead of making us wear business attire, maybe focus on getting ergonomic desks & chairs. That would at least improve our performance!

If you have never felt stuck with a team, let me tell you it's exhausting to say the least.
Either they are incompetent, or the manager sucks, or maybe you stopped vibing with the project. Whatever it may be, having a choice to switch teams is a must.
And working in a big company, that has loads of projects on going simultaneously is the best.

Everyone's a heavy lifter, and they got your back if you falter.
If you have never cried for help with some work, that is just beyond your capabilities, or that is so mundane that you feel like killing yourself, then you can't appreciate this.
Being able to rely on a colleague and helping each other out shouldn't be an issue in a big company, filled to the brim with smart people.

Working on an app you use daily, like say YouTube or Apple Maps, is way more satisfying than working on something obscure, which you can't access or which is just for internal use!
And being able to say "You're Welcome!" when your friend praises an App's feature is a cherry on top.

It's not a secret, that big companies have lots of internal tools that make life of engineers easier.
Even before React or GraphQL came into lime light, they have been used extensively internally.
Being privy to these tools can be eye opening, and may lead you to making something incredible of your own!

Superior desks, comfy chair, best of the best devices.
If you have ever worked for a small or medium company, you would know how little they care about ergonomics. Workspace is tightly packed, desks aren't adjustable, chairs are cheap.
If you are an absolute nerd and don't care about any of the stuffs mentioned above, you must care about this.
You don't want to end up in a company with a lacklustre office space, it's nothing but lifetime of lingering pain and suffering, for a short duration you spend your time there.
Which reason attracts your attention the most and which company do you want to get into? Let me know in the comments below.
]]>By the end of this post, I hope I will have convinced you to choose Ghost (Pro) for your blog.
Since I am using Ghost (Pro) it is only fitting that my first post be a review of the product. Also it makes it easy to choose the topic for the first post I want to write about!
I’m a fairly technical guy & I have always made the whole website myself. I thought making everything by myself was the best way forward, thereby never using any libraries or templates that would prevent me from reinventing the cycle.
That changed however after making several websites. Several tech changes, countless bugs later, I am done with the manual process.
After assessing several blogging platforms, & weighing them with several criteria, I have chosen Ghost (Pro) to be my partner in crime.
Ghost website has an extensive collection of comparison with alternatives. See Ghost Alternatives page for more.
There are several reasons Ghost easily wins out this comparison:
Static Site Generator together with Headless CMS make one master of Jamstack, a modern approach to building secure websites.
But after my little foray into using several Static Site Generators, here's how they pale in comparison to a full fledged solution like Ghost (Pro):
Sites like Medium, Dev.to, Write.as or micro-blogging site like have low barrier to entry, and may feel like the best choice for non technical people.
But I would like you to reconsider, because of several issues they posses:
For a detailed argument against Tumblr, read the official versus post by Ghost: Ghost VS Tumblr.
& For a detailed argument against Medium, checkout post by Ghost team: Ghost VS Medium.
Those are ghost of the past. (Pun intended)
For a detailed argument against WordPress, read what team behind Ghost have to say: Ghost vs WordPress.
Ask yourself, are you really in charge when you choose these?
Read a post by Ghost team, which plainly mentions why Ghost is way better: Ghost vs Squarespace.
Enough with the comparisons, next comes the fun part.
All the features of Ghost that make it worthwhile for every blogger!
See: Ghost Features Page or Exhaustive Feature Index for all of them.

Themes for Ghost are some of the best ones I ever encountered. The community behind theme development is great. It's mind boggling how premium the themes feel compared to a free alternative or any other platform.
Some of the theme developer behind Ghost, do build themes for other platforms, but some like Fueko build exclusively for Ghost, which says something about the platform I'm rambling about!
Some of my favourite themes from the Ghost Marketplace are:
You can find the full listing either in the Marketplace, or Themeforest!
The response time from theme creators is also commendable. For instance:

Tutorials made by the Ghost team, and so are the Documentation accompanying the site.
I wanted to add Table of Content and Google News Sitemap. I coveted those, in the theme I chose, but they were missing.
So I looked around and found aptly named tutorials on those (which shows how feature rich Ghost really is):
And here we are, both TOC & Sitemap integrated into the site. You can see the sitemap here & the table of contents in non AMP view of the site if you go to the top.


If you have implemented SEO all by yourself, you'll know the huge headache that it is!
From Sitemaps, Robots.txt, to Rich Social Cards, to Google AMP, Ghost has it all. It is simplified to the point where, you won't even know it is happening under the hood!
I don't know what else to say that would further prove how much of a lifesaver Ghost (Pro) is!
See: Exhaustive Feature Index.

The content management system is just spot on. You can start as draft, publish your posts on a schedule, or immediately release your post to the wild.
Everything is user friendly. Be it adding primary or secondary links on your sites, tags, pages, or posts!
Every feature you can dream of, it's there. Member management, staff management, import / export of data, heck even dark mode is there.
Code Injection can be done on header and footer site wide or per page basis! Imagine how easy it gets to add any external library. You don't have to fire up the VSCode anymore for a minor change.
It's fast too, I was able to easily add in 5,000 words for an article as a test, and the editor didn't even sweat.
Editor works smoothly on desktops, mobile, even on the iPad Pro (With some minor issues).
There's alternatives to the official Editor, of course, you can easily integrate iA Writer, Ulysses, etc. See all the Integrations for yourself.
See: Ghost Editor.

Never knew it was this easy. I didn't even have to lift a finger to make this happen!
Try adding "/amp" to the end of any post you see on this site and you can see the AMP view of the post. (I have customised the AMP view of my site to match the main theme!)
Google will treat your site with some love, once it sees amp pages!
See: AMP Integration.


Which means, no transaction fees on any earnings. You keep what you earn!
Any recurring payment we do, goes towards the development of Ghost.
And further development of Ghost, means more features for you and me!
See: About Ghost.


Oh the horror that is Authentication! Securely collecting and storing passwords. OAuth, SSO, Mobile Auth!
Of Course there's free services like Firebase Auth, but it doesn't even come close to the Ghost Auth's simplicity.
Ghost (Pro) comes with email authentication & advantages of using Email Auth are:
See: Exhaustive Feature Index.

Ghost (Pro) comes with Newsletter as part of the offering.
Else you would have to rely on an external service. One more expenditure averted and one less thing to work on.
While publishing a new post, you can even choose to send newsletter to members or paid members.
You can add custom content to your post that will only show up in the newsletter, and not on the website.
Thank you note to your subscriber or a secret download link for consumer delight, is absolutely possible.
See: Send Newsletter.

This is honestly the biggest reason to pick this up.
No annoying ads, just you your content and your fans, that's the vision Ghost (Pro) is aiming for.
Users mostly use adblock anyways, plus you have to beg them to disable the ads, by showing an annoying pop up, that is likely to piss off readers.
Instead you just post some premium content for free, some in exchange for membership, and some more in exchange for money.
Of course, that doesn't stop you from adding Ads later on, but still Membership might be more reliable form of income, provided content is regular and top notch.
See: Member Setup.

Seamless payment with Stripe, which also supports Apple Pay, so Apple users can have a hassle free experience.
See: Stripe Integration.

The amount of tech that can be integrated with Ghost is immeasurable.
iFrames, inline Html, Twitter, Instagram posts, anything and everything works.
Top it up with Zapier integrations and you are golden. Sky's the limit when it comes to automation overlord like Zapier.
You can send email when a member subscribes, automatically post to Social Networks.
See: Exhaustive Feature Index.

Changes take literally milliseconds.
One refresh, and you can see the updated site with the changes you made.
Things that make it fast:
See: Exhaustive Feature Index.
Ghost has well thought out & well curated list of features that makes it just right for blogging:
See: Exhaustive Feature Index.
Spend less time on your server, more time on your site.
Ghost (Pro) is a fully managed, no nonsense service by the team behind Ghost.
In the beginning of this post, I did mention my trials & tribulations doing everything from scratch.
And blogging shouldn't be about behind the scenes, rather the writing of content, & marketing. Instead of spending 80% of the time on the back-end, a blogger should be able to spend 40% of their time on writing, & 60% of their time on promoting that content.
If you can implement all the feature mentioned above, then by all means do so.
Else, this is the way to hassle free blogging.

This diagram, taken from the Pricing page, says everything you need to know about how Ghost (Pro) simplifies life of a blogger!
This is the only post you should have to read to come to a conclusion that Ghost (Pro) wins out in all dimensions and in parallel universes too. (If those exist)

If I couldn't convince you yet, checkout the Changelog for all the features in a reverse chronological order.
What do you think?
If I missed something, let me know in the comments down below, else leave your reaction. And maybe subscribe!
]]>