<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Vardan Grigoryan (vardanator) on Medium]]></title>
        <description><![CDATA[Stories by Vardan Grigoryan (vardanator) on Medium]]></description>
        <link>https://medium.com/@vardanator?source=rss-d2445cca3a3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*UM1GTH9m9ZF4NMhKqdwIyw.png</url>
            <title>Stories by Vardan Grigoryan (vardanator) on Medium</title>
            <link>https://medium.com/@vardanator?source=rss-d2445cca3a3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 06:02:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vardanator/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[42 Projects to Practice Programming Skills]]></title>
            <link>https://itnext.io/42-projects-to-practice-programming-skills-6f5acc10fec0?source=rss-d2445cca3a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f5acc10fec0</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[competition]]></category>
            <dc:creator><![CDATA[Vardan Grigoryan (vardanator)]]></dc:creator>
            <pubDate>Mon, 23 Mar 2020 20:26:36 GMT</pubDate>
            <atom:updated>2020-03-24T14:34:27.853Z</atom:updated>
            <content:encoded><![CDATA[<h4>For hardcore developers and those who are not scared to invent something new</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gXeZBy-t2u7rD2ZHIunmqw.png" /></figure><p>Before going any further, bookmark this website:</p><p><a href="http://42skills.com/">42 Projects for Programmers to Practice Programming Skills</a></p><p>Having a lot of programming project ideas is a bad thing, not sharing those with you is even worse. So, it’s a year-long challenge (something Instagram kids adore these days), tagged as <strong>#42SkillsChallenge</strong>. Here’s how to take part in this insanely complex challenge, for each of the 42 projects:</p><ol><li>Pick a project from the list.</li><li>Create a GitHub repository for the project.</li><li>Start working, try to implement everything from scratch, reinvent the wheel where possible (sometimes you have to).</li><li>When done, test it, post the tag #42SkillsChallenge somewhere in the repo (README or somewhere visible).</li><li>Share your repo with the world.</li></ol><h3>About the projects</h3><p>Some projects are simple. Some of them are hard. It’s a great way to practice your skills, especially before important technical interviews.</p><p>However, there are projects that are ridiculously complex. It might take weeks or months for you to implement them. That’s where the real rock stars survive. The one who completes all the projects first, unlocks a new level of expertise. Look at the projects, I know what I’m talking about.</p><p>Also, some projects might serve as great ideas for startupers (those who hate working and love getting rich quick). I suggest gathering a team for some projects below (or in the <a href="http://42skills.com/">website</a>) and release a pretty cool app or service and conquer the world.</p><h3>The list of projects</h3><h4>1. Web Server</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oqbmCwK88oXo7Ntw0ojZLQ.png" /></figure><p>Design and implement a lightweight web server that processes incoming network requests over HTTP protocol. Web server processes and delivers web pages to clients (usually, browsers). The pages are HTTP documents. While the primary function is to serve content, a full implementation of HTTP also includes ways of receiving content from clients. This feature is used for submitting web forms, including uploading of files (<a href="https://en.wikipedia.org/wiki/Web_server">source</a>). For an inspiration, try to imitate the Nginx web server.</p><h4>2. Packet Sniffer</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YtXgy3BtavTp9L0yXuKUPA.png" /></figure><p>A packet sniffer (packet analyzer) is used to monitor network traffic by examining streams of data packets that flow between computers on a network. To start with the project, study well the network protocols. Then dive into implementing an application that tracks down network packets and parses its content in a human readable form.</p><h4>3. Static Code Analyzer</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AlWCVttdhrr8M6z6U-56gA.png" /></figure><p>Static code analyzers are used to analyze (obviously) the source code without running it and discover issues that might lead to bugs in the running application. That way, running a static code analyzer for your project might save a lot of time in debugging. Serious projects or mission-critical systems use commercial static analyzers to check the code quality.</p><p>Design and implement your own static analyzer for any language of your choice.</p><h4>4. Spam Detector</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EXwGmfScrIq1GqPBm_lQpw.png" /></figure><p>Implement a library or a service that analyzes emails to detect spam. You are free to implement it as a browser plugin, or as a SaaS product. Try using machine learning algorithms to improve your system.</p><h4>5. Chess Engine</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*76novCkgwgtpykoL7DP10w.png" /></figure><p>A chess engine analyzes the chess board and suggests the best next move. Besides that, it might serve as an opponent in playing with the computer. Implement the next generation AI-powered chess engine. For an inspiration, have a look at the <a href="https://stockfishchess.org/">Stockfish</a>.</p><h4>6. Web Search Engine</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gutou1iV42E2Vfiae2BG6A.png" /></figure><p>My favorite one. I’ve always wanted to implement a super-duper web search engine that will compete with Google. As you can guess, nothing happened. Maybe you can implement such an engine?</p><p>Design and implement a system that indexes billions of documents worldwide, stores them in an efficient manner, and responds to user queries with most relevant list of documents.</p><h4>7. Command-Line Terminal</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TOYELVh87IbVVuF245lz3A.png" /></figure><p>This one is easy to describe. Implement a terminal app that replicates all the main Linux commands. Try to make the interface as fancy as you can.</p><h4>8. Web Browser</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ePwWfu-H-5BOu6qmyZySrA.png" /></figure><p>Sounds simple, but it’s not. First, it’s a GUI application. Next, it understands HTTP documents, and of course, it understands and properly renders HTML and CSS. And yes, it also executes JavaScript (at least the basic stuff).</p><p>So, no Chromium engine allowed. A plain web browser implemented from scratch. This one is tough. At least for me. You can skip some nasty parts and keep it basic, but still, it’s hard.</p><h4>9. In-Memory Database</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QglC1UFAhM-AggWbFqlwNA.png" /></figure><p>Another one of my favorites. The project is basically re-implementing the <a href="https://redis.io/">Redis</a>. An in-memory database keeps everything in memory. If you add a query language to it, some serious company will definitely hire you.</p><h4>10. Minimalistic OS</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tYVR-1wwXxJC0JxoLEf77g.png" /></figure><p>A dream of many. I know many programmers who dreamed to implement their own operating system from scratch. And one of the motivation for such suicidal intentions is to dive into the lowest levels of coding and getting familiar with metal. Everyone loves metal!</p><p>You can keep it simple, but at least implement several critical features for the OS. And do it from scratch, but you can have a look at the Linux kernel. After all, Linus did had a look at Minix in some ways.</p><h4>11. Video Subtitle Generator</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BPZ-UQ5o17xU-GHnN82n-g.png" /></figure><p>Implement a program that takes a video as an input, analyzes the content, does some voice processing and produces subtitles for the video. It’s fine to have a limitation on the length of the video (1 or 2 minutes would be great).</p><h4>12. Custom Cipher</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8h9Hv8-hVda8eHeYUz5iDA.png" /></figure><p>Remember those movies about hackers? Ever dreamed of becoming one? This is your chance to take a step towards that childish dream.</p><p>Design a cipher. Implement an application that encodes and decodes information based on that cipher of yours.</p><p>It would be great if you will write some automated tests to verify the strength of your creation. In other words, hack your own security.</p><h4>13. P2P Messaging Application</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ys6qh9voxQf1t8cB_pObkQ.png" /></figure><p>Implement an application for chatting with a friend. The challenge is to make it in a way that omits a centralized server and initiates a direct connection between two chat clients.</p><h4>14. Machine Translation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_T_582XcKr0Rj2IXIs18zA.png" /></figure><p>Something like Google Translate. Design and implement a service (if you got some free time, implement the app, as well) that translates a bunch of text from one language to the other.</p><p>Choose any two languages that you want. Try to make the translator smarter, train it or correct it on the way.</p><h4>15. Automated News Presenter</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*34Lzvf9-Qd8uZc2LTempLg.png" /></figure><p>You are going to like this one. Imagine the regular news readers, like Feedly. And now, picture the news presenter of CNN, talking about some breaking news, coronavirus, etc. Now, imagine a cartoon-like character, that reads news to you (to the user) like real presenters do.</p><p>Design and implement a software that collects news (generally, subscribes to RSS feeds set by the user), and reads them out loud as an animated news presenter.</p><h4>16. Payment System</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0KnMujJKXMPKXXgldlI4eQ.png" /></figure><p>You probably have heard of PayPal or Stripe or any other payment system. Now, design a new (or next generation?) payment system similar to one of those. Simulate financial transactions and prove the system is infallible to attacks. This one is hard to achieve.</p><h4>17. Relational Database Management System</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-b5cECS4aN_zh-bTntXPNQ.png" /></figure><p>Ever wondered how do databases work under the hood? Now you have the chance to build one. Design and implement a relational DBMS similar to MySQL or PostgreSQL (not necessarily supporting SQL). Don’t forget about indexing. It will be great to have transactions, but this one is not mandatory.</p><h4>18. Virtual Assistant</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hA9uaZ42zhqK1D1A72chMg.png" /></figure><p>Something like Siri, but without voice control. Just type a text, create reminders, ask questions, etc. The set of features is up to you, but the user must feel it as a solid virtual assistant application.</p><p>This project is intended for spartphones, that is, you should write it either for Android, or for iOS, or for both using some React Native/Flutter-like stuff.</p><h4>19. Garbage Collector</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wxQJTB0fktMLg8DwX5uYLg.png" /></figure><p>Quick question: what’s the difference between C++ and C#? One of the differences is that the latter has a garbage collector. Now, implement a garbage collector that can be used either as a separate service or an integrated module. The language and target are of your choice.</p><h4>20. Dropbox Clone</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NMccX6cJpM5o7DWF8k1BBQ.png" /></figure><p>Dropbox is a file sharing application. Consists of clients for almost all operating systems, including Android and iOS. It also has a huge backend. Design and implement your own version of a file sharing application that works at least for 10 users and provides 100 Mb of space to each of them. Implement both the server and the client (at least for one OS).</p><h4>21. Container Management System</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*blOpN1a_gRsqmMxUHMJ3fg.png" /></figure><p>Let me put the description of the Docker.</p><p>Docker is a set of platform as a service (PaaS) products that uses OS-level virtualization to deliver software in packages called containers. Containers are isolated from one another and bundle their own software, libraries and configuration files; they can communicate with each other through well-defined channels. All containers are run by a single operating-system kernel and are thus more lightweight than virtual machines.</p><p>Implement your own Docker.</p><h4>22. Container Orchestrator</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nt-2SNwf4-ovkODud39_8g.png" /></figure><p>It gets harder and harder. After done with Docker, design and implement an orchestrator.</p><p>For inspiration, look at Docker Swarm or Kubernetes.</p><h4>23. Antivirus Software</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zZmJ2WLVeO_rvHLuLnXtpw.png" /></figure><p>It doesn’t matter you use Linux. It’s quarantine everywhere because of the viruses. Implement a good antivirus and test it by implementing a couple of viruses. This one is not an easy task, but when you are done with implementing a Minimalistic OS, it should be easier to tackle this one.</p><h4>24. Firewall</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DB5qS1XCv2nyeLv3OYymkA.png" /></figure><p>Firewalls monitor network requests, open or close ports on the computer. They are basically the first echelon in the defense system. Design and implement a firewall software. At least try something like netstat that also has permissions to close ports or alert on suspicious network requests.</p><h4>25. Version Control System</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hq7n7hL0lZbHjeABzPEgdQ.png" /></figure><p>You most probably are using Git. You might have used SVN or even CVS. Anyways, the idea is simple. Implement a new version control system. Aim for something better than Git.</p><p>Also, remember, Linus wrote the first version of Git in two weeks or so. Accept the challenge, write your VCS in less than 13 days. In your face, Torvalds!</p><h4>26. UML Diagram Generator</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HPvAETeu4_FlNrcOomtOIQ.png" /></figure><p>Take any of your preferred programming languages that support OOP. Implement a tool that takes the project source code as an input and generates UML diagrams for it.</p><h4>27. Time Series Database</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ASiJKYghDI_LNB1t8E2liw.png" /></figure><p>It’s a database software that stores and processes time series more efficiently than regular database management systems. Find out what are time series and then design and implement a time series database system.</p><h4>28. Lock-free Data Structures</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kAf7a76e8ILcH8c7RJPl9Q.png" /></figure><p>Lock-free programming is hard to grasp. I’ve tried, merely understood.</p><p>Implement a set of lock-free data structures as a library that can be used in programming projects.</p><h4>29. Traffic Notifier</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uCIfZpEjPE24O6r-xMw3IA.png" /></figure><p>Implement an app (or a service) that notifies the user about the traffic jam.</p><p>More than that, it suggest a better route to some destination (set by the user).</p><p>This is one of those applications that might serve as a good idea for a startup. Implement a really quality service and the success is guaranteed. You can combine this one with the virtual assistant introduced earlier, and the result will be marvelous.</p><h4>30. Music Merger</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TTHfR1CzjVwlXtGv29RqWQ.png" /></figure><p>Implement a software that merges two or more music tracks together to produce a new one.</p><h4>31. Recipe Generator</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zq7MxKmRG4j0pNzHqYpPCg.png" /></figure><p>The app (or service) generates new recipes and learns through the way. So when you cook by its recipe, you then rate it to tell it how good it was. Not a fresh idea, but still can be useful.</p><h4>32. Browser Plugin for Flash Cards</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dsPNQz750OR6E5rLyI7-vg.png" /></figure><p>There were a lot of hard projects to implement. This one is a little easier. Implement a browser plugin (for any browser) that allows storing flash cards and then randomly shows them to the user (can be configured).</p><h4>33. Video Call Application</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0w_g1m3UJFWbP_xVKvEm9w.png" /></figure><p>There are several video call applications, Zoom, Skype, Google Hangouts.</p><p>But still, they work bad if the internet connection is poor. Maybe you should invent a new compression algorithm (see below) and combine it with this application to implement a new superb video call application? Not sure. Basically, this project represents PiperChat, design and implement the best quality video chat application out there.</p><h4>34. Randomness Tester</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4OgaToAjtXBpOfJOd0ue1Q.png" /></figure><p>Sounds crazy, a friend suggested this one. Write a software (or a tool), or maybe devise a formula (not sure) that tests the results of a random number generator and verifies if those are really random.</p><h4>35. Microservices Framework</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tKCSgywMqxbsYT9F8C0R7Q.png" /></figure><p>Design a pretty neat microservices framework that supports basic patterns and provides a set of implementations out of the box. Make sure you cover service discovery and microservices’ communication.</p><p>The more features you add to your framework, the better chances to win the challenge.</p><p>Choose any programming language you’d like.</p><h4>36. Functional Programming Language</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zZ7z65ItYINYzcBbYOwT9A.png" /></figure><p>Invent a new programming language in functional paradigm. Be succinct, but provide all the environment to implement programs in your language and run them painlessly.</p><h4>37. Strategy Game Engine</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t5eIzBv-2CWWSDhMZvVGAw.png" /></figure><p>One of the best ways to study OOP is through designing games. Games usually are based on engines.</p><p>Design and implement a game engine for strategy games. Preferrably, implement a game based on the engine to test it.</p><h4>38. World Simulation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xh7GCA4wDiZ3OVObUm8sDA.png" /></figure><p>Westworld is coming.</p><p>Implement a service that allows simulating complex worlds with different set of initial data. The more the details, the better is the system. This one is pretty tough, might take very long to finish it. Keep it simple when you feel stuck.</p><h4>39. Movie Recommendation System</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lHYvR9oU5qxF16j3c3xvMw.png" /></figure><p>It’s a lie, Netflix’s recommendation system sucks. Besides hand-picked lists of movies, I didn’t see a solid movie recommendation system anywhere.</p><p>Please, fix this madness. Design and implement the best movie recommendation system out there.</p><p>(<em>You might need scraping a lot of databases to collect data on movies.</em>)</p><h4>40. Pied Piper</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hg0Mw5NvY83dGUzWvsLjlQ.png" /></figure><p>Someone should do this. Design and implement a compression algorithm that compresses large files into small ones. It’s true that achieving the perfect result is very hard, but try not to limit yourself by that thoughts. Aim for the impossible, <a href="https://en.wikipedia.org/wiki/Weissman_score">https://en.wikipedia.org/wiki/Weissman_score</a></p><h4>41. Phone Video Streaming</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-tlKYkmPn1vwoG9iy8c9Nw.png" /></figure><p>An app and service allowing streaming a video from one phone to another. Share a video with a friend instantly. Pick a video file, select your friend’s device in the app and click the Stream button. That’s it, your friend’s smartphone will play the video right away.</p><h4>42. Application Builder</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oAQFun5YQnzU6K5FgV5SYg.png" /></figure><p>This one might be the hardest one. Design a system, that understands the text in a way that generates applications based on the text description. Sounds impossible. The user describes what kind of application she needs and the system generates a brand new app based on the requirements.</p><p>That’s it. The list is big; I know. The projects are not simple, that one I know, too. This is the hard way, which always leads to amazing results. Start by picking out the project you are more excited about and implement it. Also, don’t forget to share this with your friends so that the competition gets bigger and more interesting.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f5acc10fec0" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/42-projects-to-practice-programming-skills-6f5acc10fec0">42 Projects to Practice Programming Skills</a> was originally published in <a href="https://itnext.io">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Abstraction and Problem Solving with C++]]></title>
            <link>https://medium.com/tech-book-reviews/data-abstraction-and-problem-solving-with-c-c54bebf9a0ee?source=rss-d2445cca3a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c54bebf9a0ee</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[book-review]]></category>
            <category><![CDATA[books]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Vardan Grigoryan (vardanator)]]></dc:creator>
            <pubDate>Tue, 24 Sep 2019 18:20:33 GMT</pubDate>
            <atom:updated>2019-10-13T07:09:01.284Z</atom:updated>
            <content:encoded><![CDATA[<h4>Walls and Mirrors. By Frank M. Carrano, Timothy Henry, Janet Prichard.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HjQFLy2K-2aNL8d6SAVwOg.png" /></figure><p><a href="https://www.amazon.com/Data-Abstraction-Problem-Solving-Mirrors/dp/0132923726/">Amazon link to the book.</a> (you could find the same book with examples in Java).</p><p>Novice programmers often struggle at understanding data structures and algorithms. Experienced developers suggest reading Introduction to Algorithms by Cormen, Leiserson, Rivest, Stein (usually referred to as CLRS).</p><p>Many newcomers and experienced coders who’ve realized early enough that fundamental algorithms and data structures are a must for successful programming career have struggled at “hard” books like the Introduction to Algorithms (though the title says otherwise).</p><p>One of the main reasons that programmers find it hard to understand algorithms is being able to measure the complexity of an algorithm (or a data structure’s operations). Another difficulty for beginners is the variety of data structures and pitfalls in their implementations.</p><p>I found the “Data Abstraction and Problem Solving with C++” when I was searching for a great introductory material that won’t leave the reader with the easy stuff but will dive into rather complex topics with an easy to follow approach. This book is a pearl for those of you who’ve or had a similar problem. It introduces to data structures and algorithms in a way that is both engaging and fruitful. Most of the topics are discussed in great detail so that even experienced programmers will find it truly attractive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WqF8fYCTNH4dkMQBNpjiUg.png" /></figure><h3>Why algorithms and data structures are so damn popular?</h3><p>Because of companies like Google, Facebook, and alike. They tend to ask algorithmic problems at technical interviews. Strong problem-solving skills are a must for engineers working at big companies (and now at small companies, too).</p><p>Too many times people (sometimes I refer to developers as people) complain about the problems asked at companies (mostly big ones) during the interviews. Guys writing successful or famous applications get rejected from Google, Facebook, or others because they don’t know how to invert a binary tree.</p><p>These companies face challenging engineering problems every day, starting from planning and managing cheap and fast hardware resources and ending with loading the content on the device of the end-user in the fastest way. You might have written a couple of successful mobile or desktop applications, but the approach you choose in solving particular problems in the application defines your level as a programmer. For example, you can design an email client that shows the recent ten emails [in its Home screen, I guess] and it could have the best UI out there; displaying ten recent emails will work smoothly on almost any device, trust me.</p><p>Now, let’s suppose the user of your email application will receive hundreds of thousands of emails, say, in 2 years of using your application. When the user will need to search for a particular email (by subject or content or whatever), that’s where your skills may play a significant role. The way you stored the hundred thousand emails and the methods (algorithms) you used to sort and search them will now make you a <strong>rockstar developer</strong> or a hotdog beggar in the eyes of your end-user. Why so? Suppose you store all the incoming emails in an array.</p><pre>struct Email {<br>  string subject;<br>  string body;<br>  string from;<br>  date when;<br>};<br>...<br>// let&#39;s suppose a million emails is the max for anyone<br>int MAX_EMAILS = 1000000; <br>Email inbox[1000000];</pre><p>We can store the recent ten emails in any form that won’t affect the performance of the application. Issues arise when we try to manipulate thousands of emails stored in the inbox array. What if we want to search for the word “friend” in all emails? We have to scan all the emails in the array and collect ones containing the word “friend” in a separate array.</p><pre>search(word) {<br>  Email search_results[1000];  <br>  for (...) {<br>    if (inbox[i].subject.contains(word)) {<br>      search_results.insert(inbox[i]);<br>    }<br>  }<br>  return search_results;<br>}</pre><p>Obviously, the complexity of the algorithm (the speed at which it runs) is linear (i.e. it’s not perfect), so if the number of emails is N, then the number of operations performed to find all the emails containing the search term will be N (in the worst case). More than that, it also starts a search in the subject line of each email (by calling the contains() function). Considering that the search function would also try to find matches in the email body too, the running time will rise even more. So if one operation takes a <strong>millisecond</strong>, then searching among one hundred thousands of emails will take <strong>more than a minute</strong> (100 seconds to be exact). I guess you’ve never waited so long when searching for emails in any of your email clients. Here comes the need for proper use of data structures and algorithms.</p><p>Just to make the idea clear, let’s suppose we process each incoming email’s subject and body to store each word in a <strong>hashtable</strong>. The hashtable slot will refer to the email object that contains the word. When the user will search for any word, for example, “friend”, we will return the list referred by the slot of the hashtable having the “friend” key.</p><pre>search(word) {<br>  return hashtable[word];<br>}</pre><p>This is a constant-time operation and in computer science, it’s considered as the ultimate goal of efficiency. In simple words, searching among emails would take less than a second.</p><blockquote>Now imagine that you have a great startup that produces some fascinating application or provides internet service. Would you hire someone who wouldn’t master the art of problem-solving, or wouldn’t know when and how to use a hashtable (or other data structures)?</blockquote><p>Now let’s explore one of the best books for studying algorithms and data structures.</p><h3>Mmm… Algorithms</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zv5ew2Jqyrx1LPdQGYxwrw.jpeg" /></figure><p>I divide the book into three imaginary sections: “The fundamentals”, “Algorithms and faster data structures”, “Trees and Beyond”.</p><h3>The fundamentals</h3><p><strong>Chapter 1 (Data Abstraction: The Walls)</strong> introduce the concept of abstraction. The book dives into Abstract Data Types (ADT), which is then used as a base to build data structures introduced in the book. This chapter also has a short <a href="https://medium.com/@vardanator/why-cs-students-must-learn-c-as-their-main-programming-language-6d3b4f8720bd">intro to C++</a> classes that will help the reader implement an ADT (on the example of a Bag).</p><p><strong>Chapter 2 (Recursion: The Mirrors)</strong> is one of my favorite chapters. I first read a detailed explanation of the recursion in this chapter. This was the place that I’ve found out that not every function that calls itself is a recursive function (there are a couple of more rules). The chapter contains plenty of examples such as the Fibonacci sequence, the towers of Hanoi, the binary search algorithm, and more.</p><p><strong>Chapter 3 (Array-Based Implementations)</strong> and <strong>chapter 4 (Link-Based Implementations)</strong> start with leveraging arrays to implement abstract data types on the example of the Bag ADT introduced in the first chapter. The third chapter also has an interlude discussing pointers, polymorphism and memory allocation in C++ (topics that will be extensively used in further chapters). Link-based implementations show the reader how to leverage pointers to implement the Bag ADT using a link-based data structure.</p><p><strong>Chapter 5 (Recursion as a Problem-Solving Technique)</strong> is another great chapter on recursion. It discusses algebraic expressions and solving those expressions using recursion. I skipped those parts to get to the most interesting part of the chapter: Backtracking. You might already encounter the problem of the 8 Queens (how to place 8 queens on the chessboard in a way that they won’t hit each other). It has an elegant solution using backtracking. You should definitely read that part of the chapter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dxO-DwgNiAy3FA1EdBIb_g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RJ_1D14ICqyTO4lYUG7LxQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K1N1SX2bud5DwxXbeDp62g.png" /></figure><p><strong>Chapter 6 (Stack)</strong> and <strong>Chapter 7 (Stack Implementations)</strong> introduce the stack, a rather data structure adapter. Can’t say much about these chapters, the stack is a popular topic in many books.</p><p><strong>Chapter 8 (Lists)</strong> and <strong>Chapter 9 (List Implementations)</strong> are great chapters that discuss the linked list in great detail. There is this false feeling when studying linked lists that you seem to understand them unless you try to implement a list. These chapters will put things in order, and you will finally grasp linked lists completely.</p><h3>Algorithms and faster data structures</h3><p>Finally, we’ve got to <strong>Chapter 10 (Algorithm Efficiency)</strong>. This chapter will answer all those nasty questions on “Big-O”s and “small P”s and “middle F”s (the last two are fake). You will understand how to measure the efficiency of an algorithm. This will help you estimate the running time of your applications and also find better solutions to further problems that you would encounter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XrWsmeF-K2FEpvgIBHFYfw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S_-RxOkKszwVCvmDbSI-0g.png" /></figure><p><strong>Chapter 11 (Sorting Algorithms and Their Efficiency)</strong> dives into various sorting algorithms such as the selection sort and the merge sort. The chapter also discusses the efficiency of each introduced algorithm. One of the most important chapters in the book.</p><p><strong>Chapter 12 (Sorted Lists and Their Implementations)</strong> combines the linked list discussed earlier in the first part to sort data and introduce us to the sorted list. The <a href="https://medium.com/@vardanator/self-organizing-sorted-linked-list-in-c-ae24b7e0b600">sorted list</a> keeps its elements in sorted order, which might play a great deal in efficiency in applications constantly requiring data to be sorted.</p><p><strong>Chapter 13 (Queues and Priority Queues) and Chapter 14 (Queue Implementations) </strong>moves further into sorted data structures and introduces priority queues, queues that return the top (max or min) element in constant time and reorder themselves to properly handle the next request. Although the simple Queue (not the priority queue) should’ve been introduced in earlier chapters (as in previous editions of the book), these chapters make a good effort on describing the queue and its various implementations.</p><h3>Trees and beyond</h3><p><strong>Chapter 15 (Trees)</strong> introduces trees, binary trees, and binary search trees. Applications of the latter are many, so it’s a great tool in a programmer’s inventory. It’s strongly suggested reading this chapter twice if you are new to trees. Almost all advanced data structures are based on trees. <strong>Chapter 16 (Tree Implementations)</strong> is the continuation of the previous chapter. It shows the various ways to implement trees, the most popular of them is the link-based implementation.</p><p><strong>Chapter 17 (Heaps)</strong> introduces a variation of binary search trees that adapt the underlying tree to serve specific operations faster than others. For example, the max heap returns the element having the maximum value in constant time (the ultimate goal of efficient operations). Priority queues discussed in previous chapters are an example of a heap.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S_-RxOkKszwVCvmDbSI-0g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OfGJZeOfjn0cpB5nbENuvw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*peQ1jEncwSEEE_rm2vEHng.png" /></figure><p><strong>Chapter 18 (Dictionaries and Their Implementations)</strong> is one of the most important chapters in the book. The example of emails and searching among their subjects/contents that we brought at the beginning of the article used a hashtable as an efficient solution to the problem. A dictionary is the same hashtable (it’s like a nickname). This chapter also dives into topics such as collision resolution of hashtable insert operations. As a proven fast data structure, hashtables are used everywhere they fit, so you have to understand them.</p><p><strong>Chapter 19 (Balanced Search Trees)</strong> is an advanced topic for many readers. However, it is suggested to dive into the chapter as balanced search trees play a fundamental role in data-intensive applications. For example, databases leverage balanced search trees to organize table indexing. You should spend a good deal of time to thoroughly study this chapter along with <strong>Chapter 21 (Processing Data in External Storage)</strong>. Chapter 21 introduces us to B-trees which are extensively used in relational (and not only) databases.</p><p>Finally, <strong>chapter 20 (Graphs)</strong> introduces us to the popular data structure that is used in <a href="https://medium.com/free-code-camp/i-dont-understand-graph-theory-1c96572a1401">almost every gigantic internet service</a> in the world. You might’ve heard of the Facebook friends’ graph or Google’s knowledge graph. The graph data structure is extensively used in many applications and services. Though this book doesn’t dive into graphs much, it still represents a good introduction to the topic.</p><p>To sum up, understanding and using algorithms and data structures should be considered as the number one priority in your studying plans. Even if you have years of experience in making applications, studying fundamental algorithms and data structures should be the first thing bothering you. It’s worth your time!</p><h3>Final score</h3><p>Useful for programmers: <strong>10/10</strong></p><p>Fundamental knowledge: <strong>10/10</strong></p><p>Real-world projects and examples: <strong>5/10</strong></p><p>Detailed and friendly: <strong>10/10</strong></p><p>Worth buying: <strong>10/10</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c54bebf9a0ee" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tech-book-reviews/data-abstraction-and-problem-solving-with-c-c54bebf9a0ee">Data Abstraction and Problem Solving with C++</a> was originally published in <a href="https://medium.com/tech-book-reviews">Computer Science Reader</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Code. The Hidden Language of Computer Hardware and Software]]></title>
            <link>https://medium.com/tech-book-reviews/code-the-hidden-language-of-computer-hardware-and-software-bab8de93220e?source=rss-d2445cca3a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/bab8de93220e</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[books]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[book-review]]></category>
            <dc:creator><![CDATA[Vardan Grigoryan (vardanator)]]></dc:creator>
            <pubDate>Sun, 22 Sep 2019 19:41:25 GMT</pubDate>
            <atom:updated>2019-09-22T21:52:53.687Z</atom:updated>
            <content:encoded><![CDATA[<h4>A masterpiece by Charles Petzold</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*iTKtsobtfE6204SxcGTlTg.png" /></figure><p><a href="https://www.amazon.com/Code-Language-Computer-Hardware-Software/dp/0735611319/">Amazon link to the book.</a></p><p>Let’s suppose you are stuck at a desert island. You somehow manage to find food and now you need the second crucial thing to survive: a computer. How could you build a computer without… buying it?</p><p>It was my brother who’ve recommended the Code (the book) to me. I’ve read a couple of its chapters, found it ridiculously simple and thrown it away as a “stupid book” not worthy of my time. Years later I will find out that this was the only book (without an exaggeration) that I needed at the time. More than two years I was studying programming through studying C++ (the one and only). It felt good because there are so many concepts in C++ that force you to understand the low-level details of programs. However, there was that barrier that I could never cross. I couldn’t understand how is it that the CPU “understands” that it should subtract variables rather than multiplying. How could it understand that the variable x is at the address 0x12008992, and it should be loaded into one of its registers?</p><p>Building a computer became my ultimate dream as a programmer. And that was the perfect time that I was ready to read the masterpiece by <a href="http://www.charlespetzold.com/">Charles Petzold</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UoUdmo2Ymh5Sb_JGnVPztQ.jpeg" /><figcaption>Give that dev a cookie?</figcaption></figure><p>The book starts with the concept of “codes” and information encoding/decoding, introducing the Morse code, the Braille alphabet and so on. It slowly builds a strong foundation for the reader to move towards zeroes and ones. The author carefully introduces the reader to the binary numeral system and boolean algebra.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9o4DkGVJVp5c43F0BHQv8A.png" /></figure><p>After building the required fundament, the book dives into electric circuits and teaches how to build a very simple calculator. The reader will encounter many graphics depicting particular circuits in action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*TEV8I-hL-e5Rzo3_BO8hcg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*kzgRJ0C95kmlFwi7mzTZfQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*QmczmwvTtLVAk06zGTTyLg.png" /><figcaption>I&#39;ve got the colored copy</figcaption></figure><p>Eventually, you will be able to build a computer with relays from scratch and with bare hands. That’s a feeling worth everything. After building logic gates using relays and other components, the reader will have her next great moment by understanding how memory works. How can a device actually store even a single bit of information? Though modern systems differ in their complexity and structure from the CPU and RAM built in the book, the very idea that you can build a complete computer with your bare hands (even theoretically) by reading a 400-page book is kind of shocking. The author deserves a VIP spot in heaven.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*TF00t4g97OricVOV-yRLXw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*U08dAVK3b72jiXW6WV5xzA.png" /></figure><p>Finally, the book introduces an assembly language and how would it be run by the “computer” (or the CPU) built in the book. It shows the process of automating the CPU to sequentially execute instructions read from the RAM.</p><p>The book finishes with describing a graphical interface and its low-level components but doesn’t dive into the basics as it did with the computer. However, the book can be considered as a complete work that every programmer must read at least twice. After reading the book you will be inspired to build your own computer as did this <a href="http://web.cecs.pdx.edu/~harry/Relay/">guy</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*yOrrM7rFIJPRL9tRuPB0WA.jpeg" /></figure><p>Impressing, isn’t it? (though it’s built on relays).</p><h3>Final score</h3><p>Useful for programmers: <strong>10/10</strong></p><p>Fundamental knowledge: <strong>11/10</strong></p><p>Real-world projects and examples: <strong>6/10</strong></p><p>Detailed and friendly: <strong>10/10</strong></p><p>Worth buying: <strong>10/10</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bab8de93220e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tech-book-reviews/code-the-hidden-language-of-computer-hardware-and-software-bab8de93220e">Code. The Hidden Language of Computer Hardware and Software</a> was originally published in <a href="https://medium.com/tech-book-reviews">Computer Science Reader</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Computer Systems: A Programmer’s Perspective]]></title>
            <link>https://medium.com/tech-book-reviews/computer-systems-a-programmers-perspective-3ae36a119962?source=rss-d2445cca3a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ae36a119962</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[books]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[book-review]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Vardan Grigoryan (vardanator)]]></dc:creator>
            <pubDate>Sat, 21 Sep 2019 13:45:36 GMT</pubDate>
            <atom:updated>2019-09-21T14:04:07.042Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*5Cu7dQpvg2vVuP3PEAgDJw.jpeg" /></figure><p><a href="https://www.amazon.com/Computer-Systems-Programmers-Perspective-3rd/dp/013409266X/">Amazon link to the book.</a></p><p>Books that describe the fundamentals of computer organization do not dive into the topic from a programmer’s perspective. This book does what its title says, it dives into “computer systems” from “programmer’s perspective”. Almost every programmer is really curious about the inner details of program construction and execution. An ultimate goal for a programmer is to create a computer with bare hands and implement a program without a compiler (sounds kind of crazy, though).</p><p>If you’ve ever wondered about the details of an executable file loading into memory and the CPU instructions that actually execute the program, this book is for you.</p><p>The first chapters of the book are almost the same as other “computer organization” books, they tell us the story of computers, introduce to binary systems and so on. However, almost from the beginning, this book starts with a simple C program and shows how it’s compiled and then translated into machine code.</p><p><strong>Chapter 1 (A Tour of Computer Systems)</strong> of the book is a regular introduction to the history of computers and their organization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*wLJvCBku9NQZNrTHqhNqFw.png" /></figure><h3>Part I, Program Structure and Execution</h3><p><strong>Chapter 2 (Representing and Manipulating Information)</strong> tells about representing and manipulating information. It touches topics such as binary numbers, their conversion to hexadecimal, etc. It also introduces addressing basics and bit-level operations in C. It’s important for the book to be written in a way that catches a programmer’s attention. This one does it really well.</p><p><strong>Chapter 3 (Machine Level Representation of Programs)</strong> shows the reader how would a [simple] C program translate to machine code. This is one of the interesting chapters in the book.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*wLJvCBku9NQZNrTHqhNqFw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*6nuZGbDy0_2VPchzHnJQbQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*0730HkIZzRSk1f1pzHw61Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*OedaRRsqvpOLPRiD48Qe7g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*fHsbx-UV1YgVZA7zpVlovg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*twJtWJy0QrDU0nnFg5gIxw.png" /></figure><p>Furthermore, <strong>Chapter 4 (Processor Architecture)</strong> introduces how CPUs work and what instructions make the CPU complete to the extent. The chapter discusses a Y86 processor family as some “generic” way to tell about Intel x86 family without actually mentioning Intel as much as it will sound like an advertisement.</p><p><strong>Chapter 5 (Optimizing Program Performance)</strong> is a perfect resource for those programmers who are curious about the actual implementation of primitive constructs such as conditional statements and loops. It’s cool to find out that a simple <strong>goto</strong> statement along with conditional instructions (<strong>jmp</strong>s) are enough to implement a complex loop.</p><p><strong>Chapter 6 (The Memory Hierarchy)</strong> is one of my favorite chapters. Understanding the structure of computer memory along with the difference between the main memory and CPU cache (and others) is a topic that lays upon any successful project development. The chapter dives into cache memory and data locality (a super important concept for efficient coding).</p><h3>Part II, Running Programs on a System</h3><p><strong>Chapter 7 (Linking)</strong> is important for C/C++ developers mostly. Languages like C# and Java are hybrid in terms of compilation and running. C++ programs should be linked first before executing. This chapter tries its best to describe the process of linking and loading. A must read!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*oDySt2G7IOpCOHW2uP-BLQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*phmDPxkMLw6StIY2CAb4Og.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*5lInO2pa3OOGUVarTgL-NA.png" /></figure><p><strong>Chapter 8 (Exceptional Control Flow)</strong>, a boring chapter for me, but truly useful for understanding CPU interruptions and process lifecycle in general. The chapter is also useful to understand proper error handling mechanisms.</p><p><strong>Chapter 9 (Virtual Memory)</strong> is a must read that is really a must read. The point is that your programs do not have direct access to the memory but rather are accessing a complex abstraction called virtual memory. Understanding virtual memory is almost the same as understanding how memory allocation/deallocation works, what is garbage collection, how are addresses translated from virtual to physical and so on. You might read this chapter first before starting the book from its beginning.</p><h3>Part III, Interaction and Communication Between Programs</h3><p><strong>Chapter 10 (System-Level I/O)</strong>. This chapter is good as a supplementary chapter, understanding the low-level details of file creation/manipulation, is definitely a great addition to your skills as a programmer. You can though omit this chapter if you are bored.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*NeTjltbD8Ay-aoyu0GWBXA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*lF8-MDjYu5BVnGxkeWnGvA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*-tnD0XSAFHeKldo4ZSl22w.png" /></figure><p><strong>Chapter 11 (Network Programming)</strong> introduces the concept of sockets and the low-level details of socket programming. Though there are great books on network programming and a single chapter won’t be enough to master network programming on a professional level, this chapter would be a great introduction to the topic in general.</p><p><strong>Chapter 12 (Concurrent Programming)</strong> is again, a good introduction to concurrent programming and multithreading in general. If you wish to dive into the topic you have to purchase a complete book on concurrency though. However, this chapter is more than enough for most of the programmers out there. You should read it and feel the joy of reading a book till its end!</p><p>As a summary, the book is a must read for every programmer to master fundamentals of computer systems. It doesn’t matter if you are a frontend JS developer, or a backend Java developer, or an Android developer, the book will help you to understand the low-level details of your programs and also will be a good help in preparing to programming interviews.</p><h3>Final score</h3><p>Useful for programmers: <strong>10/10</strong></p><p>Fundamental knowledge: <strong>10/10</strong></p><p>Real-world projects and examples: <strong>7/10</strong></p><p>Detailed and friendly: <strong>9/10</strong></p><p>Worth buying: <strong>10/10</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ae36a119962" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tech-book-reviews/computer-systems-a-programmers-perspective-3ae36a119962">Computer Systems: A Programmer’s Perspective</a> was originally published in <a href="https://medium.com/tech-book-reviews">Computer Science Reader</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Beauty and the Bits]]></title>
            <link>https://medium.com/@vardanator/the-beauty-and-the-bits-5ffa5191f21?source=rss-d2445cca3a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ffa5191f21</guid>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Vardan Grigoryan (vardanator)]]></dc:creator>
            <pubDate>Tue, 02 Apr 2019 00:35:11 GMT</pubDate>
            <atom:updated>2021-07-26T14:10:13.820Z</atom:updated>
            <content:encoded><![CDATA[<h4>What is happening when you open a website in your browser?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nhtypL2KOwjRLlL1HPmv0Q.png" /></figure><p>Life. One of the most complicated concepts ever known to humanity. When we try to describe the life, we usually start with living organisms, such as us, humans (I apologize to the robots reading this article for the technoracial discrimination). We are composed of cells and the intercommunication of those cells produce results that we call “decisions”, “breathing”, “thinking”, “sleeping”, etc. The life itself is based upon a very basic but fundamental concept called “communication”; cells, organs, humans, animals, nature, communities, cities, countries (a hundred year later planets, galaxies, world), all communicate and keep the balance between order and chaos. It won’t be much of an exaggeration to take bits into account when describing the communication. The signal is the key concept in communication. You communicate with the light by turning the switch on or off, thus giving a signal to the light bulb. The light communicates back by turning on or off. It might just ignore the request by signaling its death, or an absence of electricity, or a cutoff in wires connecting the switch with the light, and so on.</p><p>Think about it next time you turn the switch on in your room. Think about the communication of the toothbrush bristle with your teeth while you brush them (assuming it will happen during the day). Think about your teeth and their communication with the food while you eat. A hard piece of french fries might destroy a little part of your tooth enamel, the result of the communication, which will eventually lead to a new communication between you and the dentist. Think about your brain cells that communicate together to process these words trying to deduce a general meaning that you will “understand” while reading this sentence and [probably] nodding as a result of a complex communication of the cells.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*b1kMF0gUiLfek_qb30rlJg.jpeg" /></figure><p>Communication plays a key role in computers as much as in life. The most simple electronic device is based on the communication of the electrons. We are going to dive into the beauty of the bits behind the simple request the browser makes to render the webpage on your computer. Programmers are being asked this question in technical interviews, so if you need any good reference on the topic, this might be the one you’ve been looking for.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yI--uLi9884BNB9s0kvLpw.png" /><figcaption>the big picture?</figcaption></figure><h3>The browser and the OS</h3><p>The web browser is a program used to access websites worldwide. Before you start typing the address of the website you wish to visit, you have to <strong>launch</strong> the browser application (obviously). When you hit the icon of the browser using your mouse/trackpad to launch it, the <strong>operating system</strong> recognizes the mouse click to the specific area of the screen. The OS also has the coordinates of all the rectangles of icons placed on your desktop. A double click (or a single click, as set up in your OS settings) tells the OS to search for the program in the file system. Programs usually are located in a specific directory (<em>/usr/bin</em> for example), when the OS finds the program file, which is just a file that differs from other files such as <em>acdc-hellsbells.mp3</em> by its <em>format</em>, <em>extension</em>, and <em>contents</em>. A file that can be run is called an <strong>executable file</strong>, that’s why in some systems its extension is <strong>.exe</strong> (in Windows). The browser is a file that can be executed by the OS, so it contains instructions that command the OS to do what the browser wants it to do.</p><p>The OS loads the contents of the browser program instructions into the main memory, called <strong>RAM (</strong>Random Access Memory<strong>)</strong>, or <strong>DRAM (</strong>Dynamic RAM<strong>)</strong>. It’s called the main memory because it serves as the place where instructions and data are located and can be accessed by the <strong>CPU</strong>, which in turn, is the only guy who can execute anything. The OS itself (that loads the contents of the browser into the memory) is run by the CPU.</p><p>The <strong>CPU</strong> (Central Processing Unit) is a small device that is able to do simple instructions at a time, which include <em>reading data</em> from the memory, <em>writing data</em> to memory, performing <em>arithmetic and logic operations</em>, and so on. The CPU has its little memory blocks called <strong>registers</strong>, that store a fixed amount of data (4 bytes, for example), called a <strong>word</strong>. The word is the name of the data unit that the CPU can process at a time. “Processing at a time” is called a CPU <strong>cycle</strong>. It’s similar to chewing gum. You move your mouth such that your upper and lower teeth come close together and eventually press the gum inside them to reveal the sweet juice that your tongue feels with its receptors and signals your brain that it’s tasty and you feel a little bit better. Each time your upper and lower teeth meet together and kick the gum between them, your mouth completes a cycle of chewing. You are done with the gum when you totally squeeze all the sweet taste that it has by chewing it a hundred or a thousand times. The CPU performs a simple action (usually involving data) and stores the results in a register in one CPU cycle. A program consists of tons of such actions that the CPU could possibly complete in thousands of cycles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TudE4nDtBskSdJqTHJLYRg.png" /></figure><p>The operating system <strong>loads</strong> the contents of the program using a “tool” called the<strong> loader</strong>. The loader <em>copies</em> the contents of the executable file into the main memory. When it’s ready, the CPU <em>instruction pointer</em> (a register that stores the current address of the instruction to be executed) points to the first instruction of the program. The program, i. e. the browser is now starting. It renders itself to the screen using the API provided by the operating system. The window frame, the buttons, the menu, the colors, all are rendered on the screen using the OS. The operating system serves as an environment that programs may run without intercepting with each other. The OS also monitors the actions by the program to prevent destructive intentions of the program (if any). To achieve that, the operating system incorporates the concept of a <strong>process</strong>, i.e. the running program. The program that resides in the file system is “asleep” before the loader copies its content to memory. After that, the program awakens and starts running as a process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5zWyY94gcQduXEUvE38DEA.png" /></figure><h3>Under the hood of an executable</h3><p><strong><em>Side note</em></strong><em>: For a good reference to learn this fundamental stuff from the C++ perspective and understand how the program works under the hood, I personally recommend </em><a href="https://www.amazon.com/Expert-proficient-programmer-learning-practices/dp/1838552650/"><strong><em>this book</em></strong></a><em>.</em></p><p>The executable file consists of the code segment and the data segment. When you write a program and compile it, the generated file has at least those two segments. The loader copies the contents of the executable file considering each segment and copying them to the proper memory segment. Instructions of the browser are located in the code segment (called a text segment as well). Functions responsible for requesting and rendering website content are examples of instructions. These instructions might use data which is located in the data segment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wQ0ab8tgvMdS_hqSQYc4Gg.png" /><figcaption>memory segments and the executable sections</figcaption></figure><p>The OS controls the execution of the program by incorporating the <strong>virtual memory</strong>, a mapping for the physical memory that allows each process to feel itself the only running program at a time. The OS also divides the virtual memory into blocks that control the execution of the program to some extent. For example, to call the functions properly, the OS uses the <strong>stack</strong>, which automatically allocates/deallocates memory space for the function arguments and local variables.</p><p>We write programs in high-level programming languages, such as C++. But the program, in the end, should be translated into machine code to be run by the CPU. The translation process (known as a <strong>compilation</strong>) is simplified by using middle states of translation, i.e. the program translates to an <strong>assembly</strong> language and then to machine code. Let’s take a look at the low-level representation of the logic mentioned above.</p><p>Let’s suppose we have the function request() which makes a Google search request or makes an HTTP request based on the result of the parsing of the text typed in the address bar. We introduce the following simplified <strong>blah-code</strong> (a blah-code is a mix of pseudocode and whatever the author wants). Let’s say we set the url property to 1 if the address is a valid URL and set it 0 if it’s not (a search term).</p><pre>void request(address) {<br>  if (<strong>address.url == 1</strong>) { <br>    makeHTTPRequest(address); <br>  }<br>  else { // url == 0<br>    makeGoogleSearch(address);<br>  }<br>}</pre><p><em>(Obviously, the program also defines </em><em>makeHTTPRequest and </em><em>makeGoogleSearch functions somewhere in the code.)</em></p><p>The CPU executes instructions sequentially one by one, and instructions are simple commands doing exactly one thing. We can use complex expressions in a single line in a high-level programming language such as [<a href="https://www.amazon.com/Mastering-Programming-programmer-learning-practices/dp/1838552650/">obviously</a>] C++, while the assembly instructions are simple commands that can do only one simple operation at one CPU cycle (remember the chewing?): <em>move</em>, <em>add</em>, <em>subtract</em>, XOR, and so on. The CPU fetches the instruction from the code segment of the memory, <em>decodes</em> it to find out what it should exactly do (move data, add numbers, subtract them, etc.), and executes the command. In order to run at its fastest, the CPU stores the operands and the result of the execution in registers (think of registers as temporary variables of the CPU). Registers are physical memory units that are located within the CPU so the access is much faster compared to the RAM. To access the registers from an assembly language program, we use their specified names such as <strong>rax</strong>, <strong>rbx</strong>, <strong>rdx</strong>, etc. The CPU commands operate on registers rather than the RAM cells, that’s why the CPU has to copy the contents of the variable from the memory to registers, execute operations and store the results in a register and then copy the value of the register back to the memory cell.</p><p>For example the high-level expression:</p><pre>a = b + 2 * c - 1;</pre><p>that takes just a single line of code will have the following assembly representation (a blah-code, again). Comments follow after semicolons.</p><pre><strong>mov rax, b;</strong> copy the contents of &quot;b&quot; located in the memory to the register <strong>rax</strong><br><strong>mov rbx, c;</strong> the same for the &quot;c&quot; to be able to calculate 2 * c<br><strong>mul rbx, 2;</strong> multiply the value of the <strong>rbx</strong> register with immediate value 2 (2 * c)<br><strong>add rax, rbx;</strong> add <strong>rax</strong> (b) with <strong>rbx</strong> (2*c) and store back in the <strong>rax</strong><br><strong>sub rax, 1;</strong> subtract 1 from <strong>rax</strong><br><strong>mov a, rax;</strong> copy the contents of <strong>rax</strong> to the &quot;a&quot; located in the memory</pre><p>A conditional statement suggests that a portion of the code should be “skipped”, for example, calling request(“world better place how”); means the if block will be <em>omitted</em>. To express this in the assembly language, the idea of <em>jumps</em> is used. We compare two values and based on the result we jump to a specified portion of the code. We label the portion to make it possible to “find” the set of instructions. For example, to skip adding 99 to the register rbx, we can “jump” to the portion labeled “MEH” using the unconditional jump instruction jpm.</p><pre>mov rax, 2<br>mov rbx, 0<br><strong>jmp MEH</strong><br>add rbx, 99; will be skipped<br><strong>MEH:</strong><br>add rax, 1<br>...</pre><p>The jmp instruction performs an <strong>unconditional jump</strong>, i. e. starts the execution of the first instruction at a specified label without any condition check. The good news is that the CPU provides <strong>conditional jumps</strong> as well.</p><p>The body of the request() function will translate into the following assembly code (simplified), where the je is interpreted as “jump if equal to” and jne as “jump if is not equal to” (based on the results of the comparison using the cmp instruction):</p><pre><strong>mov rax, address.url</strong>; copy the &quot;address.url&quot; into the <strong>rax</strong> register<br><strong>cmp rax, 1</strong>; <br><strong>je IS_URL</strong>; jump if url is 1<br><strong>jne IS_SEARCH_TERM</strong>; jump if url is 0<br><strong>IS_URL:<br></strong>  <strong>call </strong>makeHTTPRequest<br><strong>IS_SEARCH_TERM:<br></strong>  <strong>call </strong>makeGoogleSearch </pre><p>The browser executable file consists of thousands of lines of similar codes but in the form of zeroes and ones, where each combination specifies a command or data (10001 means add, 01101 means move, etc.).</p><h3>Typing the address and pressing the “Enter”!</h3><p>The OS handles user events such as mouse click or keyboard key press and passes them to the running application. When you click on the address bar of the browser, type the address of the website and hit the “enter” button, all of that events are passed to the browser by the OS. The OS in its turn gets them from the CPU via <em>interrupts</em>. An <strong>interrupt</strong> is the “hey” of the digital world. Imagine you take a walk and think around the pitch of your startup the aim of which is to convince the investors that all you want to do is to make the world a better place (instead of making a sh*tload of money and the opportunity to sign on your fans’ boobs (which are hot chics, obviously)); and someone interrupts you with a “hey!”, you take a pause from your obviously fantastic thoughts and turn to that someone with a “why C++ is better than C#” face and that someone asks you how to get to the nearest station blah blah. You answer them and get back to your obviously fantastic thoughts. The “hey!” <strong>interrupted</strong> you from your “default” routine the same way the CPU is interrupted when the user clicks or types something. These events are then passed to the browser which properly reacts to them by rendering letters on the address bar while you are typing, for example.</p><blockquote>An interrupt is a signal to the processor emitted by hardware or software indicating an event that needs immediate attention (<a href="https://en.wikipedia.org/wiki/Interrupt">Wikipedia</a>).</blockquote><p>After typing the address, for example, “facebook.com”, and hitting the “enter” by signaling the browser to start loading the contents of the website, the browser starts the parsing of the address. Most of the browsers allow you to search the term rather than enter the address completely, for example, in <em>Chrome</em> (I use Chrome), typing “facebook” without a “.com” performs a Google search and results in a list of websites that match the query the most, and obviously the first result would be the link to facebook.com. To achieve this and also to properly request the website, the browser parses the contents of the address bar to find out what exactly is it. Is it an “asdf”, or is it an IP address (138.201.20.123) or is it a fully typed address of the website (“http://facebook.com”)? In any situation, the browser “must” perform a <strong>network request</strong> to the target server to retrieve the contents of the website to be rendered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yogm3rMVMultOvrnPXjCkQ.png" /></figure><h3>Name lookup</h3><p>Let’s suppose that you’ve typed “http://facebook.com” and now you are waiting for the browser’s response. The browser has to somehow find the one and only server that contains the contents of the website and ask that server to send the contents over. It’s the same as if you look for the guy named Valod that lives on the planet Earth and has a tattoo of a mermaid on his left shoulder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*t7ld9xk9R81ktajZS98fVg.jpeg" /><figcaption>This might be our Valod. (image source: TNW)</figcaption></figure><p>To do so, the browser has to lookup the actual IP address of the server that is mapped to the name “facebook.com”. The browser first performs a DNS lookup. <strong>DNS</strong> stands for Domain Name Server, a server that holds the names mapped to the IP addresses. The lookup starts from your local internet provider to so-called root internet servers to get the name servers first for the “.com” top-level domain and then for the “facebook.com”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AfnNF4ez64N3xRr1ucyJ9Q.png" /></figure><p>The browser caches the response to access the same website faster by skipping the DNS lookup phase. It usually takes microseconds to retrieve the IP address of the website, the browser then makes an HTTP request to the server. This is where the hard stuff begins.</p><h3>Network requests</h3><p>Both to make the DNS lookup and to make an HTTP request to the server, the browser has to do it over the internet. To be able to do so, it uses a concept called sockets. <strong>Sockets</strong> are abstractions provided by the operating system and allowing to access a remote computer on the other side of the planet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D5x909HPRkBQBMjsEmyXMw.png" /></figure><p>Sockets are a way of accessing the <em>other world</em>, in order to send to or receive data from the other world, a stable <strong>connection</strong> should be established between the worlds using sockets. Sockets are files that are treated differently by the OS. The program tells its intention to access the internet by telling the OS to create a socket for it, a special file the program could write data that would be transferred via the network (could be a local network as well). Whenever the program writes something to the socket, the OS transfers it to the specified endpoint (another socket in another computer). So the browser creates a socket (asks the OS to create one) after the user types the address of the website and fills the socket with data regarding the request. It doesn’t matter if the request is a DNS lookup or is an HTTP request to the Facebook’s server, it happens using a socket. The type of the socket the browser creates is a client socket because it should be used to “ask” for something. The one that serves the results (the Facebook server) <strong>listens</strong> for incoming network requests and creates its own “server” socket to handle requests and serve data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t6kmlf0I2HXQaXwKv9UiWg.png" /></figure><p>How would the OS cope with several programs that need network access? For example, suppose you are opening the facebook.com in your browser and chat with your friend at the same time using the Skype desktop application. Both applications require a network connection and both ask the OS to create sockets for them. Eventually, the OS creates two sockets for two different applications. To know the difference between these sockets, it uses <strong>port numbers</strong>. Each socket has its unique port number which cannot be used by any other application. For example, the socket created for Skype uses the port 5678, and the socket created for the browser uses the port 8765. This way the OS can distinguish the data sent by the browser from the data sent by Skype and also can correctly pass the response to the proper application. The port number is specified by the program developer and should be chosen wisely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9fAhW1fB7I63cfhK6CBLJA.png" /></figure><h3>Why you can’t access the internet from your pocket calculator</h3><p>It doesn’t have a network adapter, a device that makes it possible for bits to flow from a computer to another computer by wires (or radio signals). This is the lowest level of network communication, called the physical layer. Data is sent via the wires as a sequence of bits which are then collected into something meaningful by the receiver (the beauty of the bits). The form of communication is known as a <strong>protocol</strong>. The protocol defines the form of the data, the exact location of data and headers describing the data in the packet. The <strong>packet</strong> is the unit of information passed through the network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vEPdiGLcZwgddwYpqRu9Ew.png" /><figcaption>(<a href="https://www.dummies.com/programming/networking/cisco/cisco-networking-packets/">image source</a>)</figcaption></figure><p>To transfer the packet, the transferrer should mark it somehow for the receiver the same way the mail is marked with stamps, the delivery address, and the sender address. The protocols exist for that purpose. Each layer of the network model adds level-specific metadata to the packet. The packets formed by the browser are <strong>HTTP</strong> (HyperText Transfer Protocol) documents sent over <strong>TCP</strong> (Transmission Control Protocol).</p><p>An HTTP document consists of two parts, the <strong>header</strong>, and the <strong>body</strong>. The header of a document contains the metadata related to the request and the document body. For example, it may contain the details of the browser that made the request, the size of the data located in the body of the document, and so on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d9xtQzr079S0xsU58_1hPA.png" /><figcaption>Google Chrome debug tools</figcaption></figure><p>When you request the contents of facebook.com, the request-document doesn’t contain a body, it only contains a header describing what does the browser need from the server. The server responds with a document that contains the full contents of the requested web page in the body of the HTTP-document.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MDOkSnODla-EhRdN138bJA.png" /><figcaption>(<a href="https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/HTTP_Basics.html">image source</a>)</figcaption></figure><p>So the following happens during a network communication:</p><ul><li>the browser creates a socket (by specifying the port number, the transmission protocol);</li><li>the browser creates an HTTP request document;</li><li>the browser writes the HTTP-document into the socket and commands the OS to make the request;</li><li>the OS transforms the data into TCP packets and passes to the network adapter;</li><li>the network adapter sends the bits of packets to the network;</li><li>the packet(s) are being received from the server’s adapter, which then passes it to the higher levels of the network model;</li><li>the OS of the server fetches the data from the received packet and passes to the web server;</li><li>the web server parses the contents as an HTTP-document and creates the response HTTP-document;</li><li>the web server sends the response the same way the client sent it;</li><li>the client receives the response and renders the contents as a web page.</li></ul><h3>Serving the request</h3><p>A single computer that runs a special software called a web server might be considered as a server. The web server creates a server socket and listens for incoming connections on port 80 (the default HTTP port). You can create your own web server by designing an application that creates a socket, listens for the port 80, and accepts incoming connections and serves data following the rules of the HTTP protocol.</p><p>Facebook (and lookalikes) consists of thousands of servers in a complex architecture to serve millions of users as fast as it might be achieved.</p><p>The request comes to one of the <em>front</em> servers, which decide which processing server should serve the request that has the minimum load and is at the nearest location [geographically] to the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jr_mQreD_7OvnCb4ta6xwQ.png" /></figure><p>Processing the request most of the time requires accessing databases. Let’s suppose you’ve opened the facebook.com in your browser and didn’t log out the last time you visit it. So the browser stored the information regarding your last authorization in its “memory” and now requests the facebook.com by passing that information (usually a request key in a form “kjhlkjhjhl1234324WEASDASF34534FDFGDfhhf877”) along with the HTTP-request (in the HTTP header). The Facebook servers authorize the request and fetch the user data that is mapped to the request key specified in the HTTP request.</p><p>Authorization involves accessing in-memory databases in order to efficiently retrieve user information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZEREnNZb3vlP-P4s3x8ZzA.png" /></figure><p>Finally, having the user information (authorizing the request at the same time), now the news feed (the wall, Mr. Snow) can be fetched from the database. To make this retrieval faster, a database index is used which usually represents a B-tree. The final content of the wall and other user-related data (didn’t fit in this simplified version of the story) is then sent as an HTTP-response document.</p><h3>Rendering the server response</h3><p>When the browser receives the HTTP-response from the server, it starts by looking at the header of the document. The header specifies the type of the content, whether it’s an HTML text, or a binary data to download, or an image to render on the screen, and so on. Usually, the response contains the HTML text of the web page. The browser discovers this by examining the HTTP-document for the Content-Type header.</p><blockquote>Content-Type: text/html</blockquote><p>Now the browser has to parse the HTML and show the buttons, input boxes, tables, links, images, etc. on the page. The browser constructs so-called DOM to conveniently manage and render the web page. <strong>DOM</strong> (Document Object Model) defines the model for the document that can be pictured as a tree consisting of HTML elements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GfLr9jBhYPv6fDt4WKwR3A.png" /><figcaption>(image source: Wikipedia)</figcaption></figure><p>The image above illustrates the DOM constructed from the following HTML code:</p><pre>&lt;html&gt;<br>  &lt;head&gt;<br>    &lt;title&gt;My title&lt;/title&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;h1&gt;A heading&lt;/h1&gt;<br>    &lt;a href=&quot;&quot;&gt;Link text&lt;/a&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>The HTML is the declaration of how the content should be rendered by the browser. Besides HTML, the browser deals with CSS and JavaScript as well. The CSS specifies the styling of the elements.</p><h3>JavaScript</h3><p>JavaScript adds some dynamicity to elements. The browser represents a mini version of the OS that runs a JavaScript program inside of it. The OS doesn’t actually know about the JavaScript and even about the browser’s capability to run a “program”. It’s like renting an apartment from someone and renting a room out to someone else without the knowledge of the landlord.</p><p>For example, Facebook’s main page won’t make a login request unless you type the login and the password in the input fields. It must have a JS-code that checks if the fields are not empty before enabling the “Submit” button. Take a look at the following JS blah-code (a blah-code can be ill-formed, never mind)</p><pre>function checkFields() {<br>  let login = document.getElementById(&quot;login&quot;);<br>  let pass = document.getElementById(&quot;password&quot;);<br>  if (login.value != &quot;&quot; &amp;&amp; pass.value != &quot;&quot;) {<br>    document.getElementById(&quot;submit_button&quot;).value = 1;<br>  } else {<br>    document.getElementById(&quot;submit_button&quot;).value = 0;<br>  }<br>}</pre><p>The browser takes care of the code. It creates an environment for the JS to be executed and provides access to the elements rendered from the HTML text fetched from the server (the JS code is fetched from the server as well). To achieve the finest result, the browser contains a fully functional JavaScript <strong>virtual machine</strong>, such as Google’s V8. It runs the JS by <em>interpreting</em> it (not compiling), which means that instructions are being executed one by one by the virtual machine (V8). To execute each command, it should be translated into machine code, because the final executor of the command must be the CPU. So the translation is done by the virtual machine, and the browser runs the translated code as its own. Similar to our apartment renting example, it’s like asking the landlord for a spare key and giving it to our guest who rents the room from us.</p><p>In the end, I hope I managed to express most of the beauty of the bits. If you find something missing (don’t), or any issues/errors (just, don’t), let me know in the comments.</p><figure><a href="https://usejournal.com/?utm_source=medium.com&amp;utm_medium=noteworthy_blog&amp;utm_campaign=tech&amp;utm_content=guest_post_image"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PYxBP_WV7LI6zc-zdUkNqQ.png" /></a></figure><p>📝 Read this story later in <a href="https://usejournal.com/?utm_source=medium.com&amp;utm_medium=noteworthy_blog&amp;utm_campaign=tech&amp;utm_content=guest_post_read_later_text">Journal</a>.</p><p>👩‍💻 Wake up every Sunday morning to the week’s most noteworthy stories in Tech waiting in your inbox. <a href="https://usejournal.com/newsletter/noteworthy-in-tech/?utm_source=medium.com&amp;utm_medium=noteworthy_blog&amp;utm_campaign=tech&amp;utm_content=guest_post_text">Read the Noteworthy in Tech newsletter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ffa5191f21" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Warning: Your programming career]]></title>
            <link>https://medium.com/sololearn/warning-your-programming-career-b9579b3a878b?source=rss-d2445cca3a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9579b3a878b</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[careers]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Vardan Grigoryan (vardanator)]]></dc:creator>
            <pubDate>Sat, 12 May 2018 15:57:19 GMT</pubDate>
            <atom:updated>2020-04-17T23:16:33.114Z</atom:updated>
            <content:encoded><![CDATA[<h4>How not to get lost in the dark forests of programming</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SNOF9EOlDnAViwEZAoFwmg.jpeg" /></figure><p>The main thing that was bothering me while I was just starting my coding career was the language/technology choice. What should I learn, where should I start? What should I know to get my first job as a programmer? Back then (almost 10 years now) there wasn’t Coursera, or Udemy or <a href="https://www.sololearn.com/">SoloLearn</a>. I wasn’t able to figure out the exact direction, the complete path leading to a successful job myself. The highly paid, fully fed, kindly treated job of the astronaut of the 21st century: the programmer.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.listle.io%2Fembed%2F124965672&amp;url=https%3A%2F%2Fwww.listle.io%2Fembed%2F124965672&amp;image=https%3A%2F%2Fwww.listle.io%2Ffavicon.ico&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=listle" width="650" height="190" frameborder="0" scrolling="no"><a href="https://medium.com/media/26ff2e1b2d0ffaee13dc48f64beb4aeb/href">https://medium.com/media/26ff2e1b2d0ffaee13dc48f64beb4aeb/href</a></iframe><p>The very same problem still exists: beginners are stuck at the choice, there isn’t a straight path to become a good programmer and the community isn’t so warm in welcoming the newbie questions like “iz pythn a gut lang???”. The path to a successful programming career is even vaguer than before. You (supposing you are a beginner) should choose between <a href="https://www.amazon.com/Expert-proficient-programmer-learning-practices/dp/1838552650/">C++/C++11/C++14/C++17/C++20</a>, Java, C#, Kotlin, PHP (what?), Python, Node.js, JavaScript, (wait, with Angular, React or Vue?) and so on.</p><h3>The language, the technology, or the skills?</h3><p>To answer your main question, I have to ask you one first. <strong>What do you want?</strong> Are you excited to build mobile apps, a website, a website like Facebook or a website like Medium, or do you want to build a desktop application like Photoshop? Maybe you are fully into the game development? Mobile? Desktop?</p><p>The most intelligent way to answer “<strong>what should I know to get hired at a tech company as a software engineer</strong>?” is to find out the main skills you should master to successfully pass the technical interview. But first, we should put things in order, let’s dive into the programming world, its countries and cities, its cultures and wars, its wins and losses. For those who aren’t patient enough, scroll down to the “Preparing for Coding Interviews” section.</p><p>Exploring the world of programming brings us to 3 main platforms:</p><ol><li><strong>Web</strong> (Google Search, Facebook, Amazon, Twitter and others)</li><li><strong>Desktop</strong> (Dropbox, Photoshop, Visual Studio, Skype and others)</li><li><strong>Mobile</strong> (<a href="https://www.sololearn.com/">SoloLearn</a>, Instagram, Uber and others)</li></ol><p><em>Most of the services above exist in almost all of the platforms, for instance, Skype is a desktop, mobile and (although poorly done) web application, Twitter is a web and mobile application and so on.</em></p><h4>Web</h4><p>Web itself is a huge concept in this context, to shed light on it, we should separate it into so-called front-end and back-end, the latter being my personal favorite. Front-end is what you see, back-end is what you need in order to see what you see. Again, front-end is the look and feel, back-end is the servers running the application which processes user requests, handles database queries and so forth.</p><p><strong>Front-end.</strong> If you want to master the look and feel, i.e. build websites that are so beautiful that users fall in love, you should know HTML (the look), CSS (the look and feel), JavaScript (the feel). This isn’t just enough, using pure JavaScript is not enough nowadays, so you have to choose the right framework, currently popular Angular, React or Vue. Which one to choose is mostly based on the company you like the most, Google or Facebook? Go with Angular if you like Google, and with React if you like Facebook. If you don’t like any of them (weird), go with Vue. Simple! Besides these, you should master some fundamental concepts, like the inner workings of the HTTP Protocol, be familiar with web servers (at least you should not be scared of names like Apache or Nginx). Being a front-end developer means you get the data to render (beautify for users) from the back-end, so some minimum understanding of what an API is, what is JSON (and why it’s better than XML) is a must. (If anything sounds way too unfamiliar, check the References section at the end of this post).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*mJ_4xsEgEizLg9xenU1yUw.jpeg" /><figcaption>One of many memes on the web describing the difference between front-end and back-end</figcaption></figure><p><strong>Back-end. </strong>The unseen truth, the untold story. In the old days, knowing PHP was enough to call yourself a back-end developer, then Microsoft introduced ASP.NET. They were fighting each other until Node.js came and put things in their best order. Some concepts of event-driven development are best applied at Node.js, so if you choose it, you are doing a good favor to your project.</p><p>The confusing part of the back-end is its language diversity, well, you can use any language you want at the back-end, the point is, “back-end” is a short name for “query database, process data, respond to client and do it as efficient as you can” and choosing the “right” language/technology/database is not an option. While some developers go with Relational Databases like MySQL or PostgreSQL, newcomers choose the dark side, NoSQL (like Cassandra or MongoDB). The choice is really yours, but I’ve got a simple formula. Do you have a strict schema for your data and it won’t change much in the near future? Choose Relational Database. Do you have more than million visits per minute? Change to NoSQL (painfully). Does your product change rapidly? Choose NoSQL. Let’s say you chose the side, now, what concrete technology should you choose? Do you like Microsoft and you have Windows Servers? Choose MsSQL. Do you like Oracle? Choose Oracle. Are you ok with Oracle, but you hate Microsoft at the same time? Choose MySQL. You just really don’t want to hurt anyone? Choose PostgreSQL.</p><p>NoSQL comes in tricky. It really depends on your service and data architecture. You’ve got just documents and some weak connections among them? Choose MongoDB. You need to store a huge bunch of key-value pairs? Choose Redis. You are working with a graph-like structure (Facebook friends graph, Google knowledge graph, etc.)? Choose Neo4j. Aren’t really sure what exactly you need, but you feel that you need all of them? Choose ArangoDB.</p><p>While database holds all the necessary data, you should define an API through which your clients can request and read/write to the database. The most useful option here is Node.js, though you can go with PHP or ASP.NET or Ruby or Python, my personal recommendation would be Node.js. Well, Facebook uses PHP at its backend, kind of. They rewrote a huge part of PHP in C++. Some use Python while others prefer Ruby. It’s true that you can use almost any language at the back-end, for instance, <a href="https://www.amazon.com/Expert-proficient-programmer-learning-practices/dp/1838552650/">Google uses C++</a>, Java and Python (along with Go). For low-level data processing, C++ fits the best, for background jobs like updating user’s friend recommendations, Java is a good option. For data analysis or natural language processing or for nowadays highly popular AI-related tasks you most probably will use Python.</p><p>Again, besides various languages, frameworks, databases at back-end, there are some core concepts that you have to master.</p><ul><li><strong>Caching</strong>. Starting from the CPU cache (with different levels) and ending with browser cache. Caching used everywhere, for high load services like Google Search or Facebook, caching is extremely necessary.</li><li><strong>Servers</strong>. While you might think this is related to the hardware (which will be great if you know how to setup several computers to work as one piece in storing and processing data), for the back-end developer server means the web server. Popular web server nowadays is Nginx and knowing how to setup and configure it will pay highly in your future endeavors.</li><li><strong>Sockets</strong>. Cornerstone of the network programming. Everything you send/receive via network is done by sockets. Knowing low-level details of socket programming is a good bonus in your skills inventory (knowing difference between TCP sockets, UDP sockets and what are WebSockets is a huge plus).</li><li><strong>Database Design</strong>. No matter what DBMS you choose or have to work with, operating with data will be one of your main tasks. Ability to see the complete picture, visualize data and connections between data units is a skill you will master during your whole programming career.</li><li><strong>Security</strong>. As other concepts mentioned above, this one is very broad, too. You can’t master any of them completely, so you should at least be familiar with some best practices such as storing password hashes rather than as plain texts. Checking requests via API token, verifying user permissions for each request and so on.</li></ul><h4>Desktop</h4><p>We will talk about the part of the desktop application that actually makes it a desktop application. There are tons of applications on Desktop platforms that need specific skill set, for instance, Photoshop is working with images, and knowing image processing algorithms and techniques is a must if you want to write something like Photoshop. Knowing socket programming is a must if you want to write something like Dropbox. Knowing how to engineer a compiler is a must of you want to build a compiler or IDE like Visual Studio. We won’t touch upon specifics, let’s just explore the languages you most probably will use if you want to work on desktop platform.</p><p>When it comes to languages for desktop applications programmers are having a hard time choosing among <a href="https://www.amazon.com/Mastering-Programming-programmer-learning-practices/dp/1838552650/">C++</a>, Java or C#. There is a simple formula to make the right choice: if you like Microsoft, use C#. If you like Oracle, use Java. If you think that a programming language should not be owned by a particular company, <a href="https://www.amazon.com/Expert-proficient-programmer-learning-practices/dp/1838552650/">use C++</a>. If this isn’t helping much, let’s discuss the actual sub-platforms. If you write software only for Windows users, C# is the best choice. It’s kind of obvious as both are products of Microsoft and they fit together the best. Though C# developers insist that after the release of .Net Core, C# can be used in Linux environment, too, <a href="https://www.amazon.com/Expert-proficient-programmer-learning-practices/dp/1838552650/">I personally suggest to go with C++</a> if you want to cover Linux. The point is, C++ was been created as a cross-platform programming language, which works great in all operating systems out there (yes, even MacOS). Well, cross-platform in this context supposes that you have to compile your C++ project in all operating systems separately to ship “different” executables of your application for each concrete OS. And, honestly, C++ lacks any GUI. The greatest excuse for that is the fact that “C++ is for hardcore developers, and hardcore developers use nothing but Terminal (command line interface)”. However, kind developers gathered together and created Qt, the very best cross-platform GUI library that fits perfectly with C++.</p><p>Finally, if you get angry with the <a href="https://www.amazon.com/Expert-proficient-programmer-learning-practices/dp/1838552650/">complexity of C++</a> and the fact that you should connect a separate library like Qt to have complete GUI experience for your users and you hate to compile and ship different executables of your product for different OS, go with Java. Java has its virtual machine which makes it easy to ship the executable. Your application works equally fine on any OS where JVM (Java Virtual Machine) is installed.</p><h4>Mobile</h4><p>When speaking of Java, first thing that comes to mind is Android. Long before Kotlin has been introduced to the world, Java was the de facto language in order to implement Android apps. Nowadays, Kotlin takes hearts of developers and allows even better experience of developing apps for Android platform. So, if you want to make Android apps, you should choose between Java and Kotlin. To make the correct choice, we should look behind the scenes. The point is, Google is not so cool with Oracle. Oracle owns Java and Java dominates in Google’s Android, so to have some flexibility here, Google had to introduce an option for the light side (or the dark side, up to you) and introduced <strong>Kotlin</strong> as “<em>wow, why use Java if there is such a great language we support</em>”. I personally suggest you start with Kotlin if you are just starting your Android developer career, though to be a competent developer in the market, you have to support previously implemented apps in Java, so, knowing Java will be a good bonus in your CV.</p><p>And finally, iOS. The iLand. An entirely different story. For a long time Objective-C was the dominant language for iOS and to be completely honest, mastering Objective-C required a serious approach, tough look and some good perseverance. That was the main issue of relatively small number of Objective-C developers out there and Apple finally made the right move by introducing <strong>Swift</strong>. Swift is much easier to master than Objective-C, which lead to increase in the number of iOS developers. So, to be an iOS developer, you need to go with Swift, but to be a really confident developer, it is suggested to master Objective-C to support apps (tons of apps) already written in Objective-C.</p><p>I should mention React Native here, as it allows to write apps for both Android and iOS platforms using just JavaScript, however, as a new and rapidly changing player in the market, let’s just consider that it exists and you already can write simple apps if you know only JavaScript.</p><h3><strong>Preparing for Coding Interviews</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-m_hxcxFCO0_-ND-FBFz6g.jpeg" /></figure><p>There are concepts that are fundamental in programming world. Most of the technical interviews are meant to discover your problem solving skills and knowing those concepts, so besides mastering a programming language, you should be familiar with the concepts that are somewhat required in programmer’s arsenal. Here’s an excerpt from my recent lesson post in <a href="https://www.sololearn.com/">SoloLearn</a> (below are the links to Android and iOS apps).</p><ul><li><a href="http://bit.ly/sololearn-android">SoloLearn: Learn to Code for Free - Apps on Google Play</a></li><li><a href="http://bit.ly/sololearn-ios">SoloLearn: Learn to Code on the App Store</a></li></ul><p>To successfully prepare for coding interviews you should be confident in the following areas:<br>1. Algorithms &amp; Data Structures<br>2. Computer Organization &amp; Operating Systems<br>3. Coding<br>4. System Design</p><p><strong>Algorithms &amp; Data Structures</strong> <br>This is the most wanted skill set for programmers. Here are the subjects every programmer must be familiar with:</p><p><strong>Algorithm Complexity:</strong> Big-O notation and how to calculate algorithms complexity; knowing which algorithm is better based on their complexity, e.g. O(N) vs O(logN).</p><p><strong>Basic Data Structures &amp; adapters:</strong> Array, Linked List, Stack, Queue.</p><p><strong>Sorting &amp; Searching:</strong> Knowing various sorting algorithms helps you to identify the best possible implementation for your projects. For practice, try to implement insertion sort, selection sort or merge sort and spot the difference between linear search and binary search.</p><p><strong>Trees &amp; Graphs:</strong> Trees and Graphs are everywhere, starting from “friends graph” in Facebook to “knowledge graph” in Google Search.</p><p><strong>Hashtables:</strong> Being one of the most efficient data structures in the world, hashtables are always a good choice. You should be able to implement a Hashtable and be familiar with techniques to solve collisions.</p><p><strong>Computer Organization &amp; Operating Systems</strong> <br>It is strongly advised to be familiar with topics like:</p><ul><li>Bitwise operations</li><li>How does the CPU execute machine code</li><li>What’s the difference between static RAM and dynamic RAM</li><li>What kind of OS kernel types exist</li><li>What’s the difference between “mutex” and “semaphore”</li><li>What is a deadlock and what is a livelock</li></ul><p><strong>Coding</strong> <br>You should have really good knowledge of at least one programming language. Knowing all the pros and cons, best practices of your favorite language will always help you write efficient, elegant and readable code.<br>It is highly recommended to practice by solving challenging problems, such as (all the problems below could be found on <a href="https://www.sololearn.com/">SoloLearn</a>):</p><ul><li>The Josephus Problem</li><li>Tower of Hanoi</li><li>String Compression</li><li>Balanced Parenthesis</li><li>Twin Prime Numbers</li></ul><p><strong>System Design</strong> <br>Knowing Object-Oriented Programming is a must for a modern programmer. <br>System Design means thinking about the whole system, being able to design its architecture, dissect it into classes, define object interactions. <br>To be prepared try to answer the questions below:<br>- How would you design Google Search? What if there are millions of simultaneous requests per second?<br>- How would you implement Facebook’s friend search?<br>- Why would you use a Relational Database Management System?<br>- Why would you use a NoSQL DB?</p><p>It is highly recommended to know and use the correct design patterns. For example, you should know the difference between a Composite and a Decorator.</p><p>While junior developers are mostly required to have good problem solving skills and your first job won’t require knowing all the points listed above, this list will be a good help to plan your career.</p><p>For a good reference to learn C++ and understand how the program works under the hood, <a href="https://www.amazon.com/Expert-proficient-programmer-learning-practices/dp/1838552650/"><strong>see this book</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9579b3a878b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sololearn/warning-your-programming-career-b9579b3a878b">Warning: Your programming career</a> was originally published in <a href="https://medium.com/sololearn">Sololearn</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to think in graphs: An illustrative introduction to Graph Theory and its applications]]></title>
            <link>https://medium.com/free-code-camp/i-dont-understand-graph-theory-1c96572a1401?source=rss-d2445cca3a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c96572a1401</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Vardan Grigoryan (vardanator)]]></dc:creator>
            <pubDate>Wed, 21 Feb 2018 18:11:38 GMT</pubDate>
            <atom:updated>2022-04-01T06:38:44.244Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z6qfDmoZcZheiTxEcPOQJQ.png" /><figcaption>Graph theory can be difficult to understand</figcaption></figure><p>Graph theory represents one of the most important and interesting areas in computer science. But at the same time it’s one of the most misunderstood (at least it was to me).</p><p>Understanding, using and thinking in graphs makes us better programmers. At least that’s how we’re supposed to think. A graph is a set of vertices V and a set of edges E, comprising an ordered pair G=(V, E).</p><p>While trying to studying graph theory and implementing some algorithms, I was regularly getting stuck, just because it was <strong>so</strong> boring.</p><p>The best way to understand something is to understand its applications. In this article, we’re going to demonstrate various applications of graph theory. But more importantly, these applications will contain detailed illustrations.</p><p>While this approach might seem too detailed (to seasoned programmers), but believe me, as someone who was once there and tried to understand graph theory, detailed explanations are always preferred over succinct definitions.</p><p>So, if you’ve been looking for a “graph theory and everything about it tutorial for absolute unbelievable dummies”, then you’ve come to the right place. Or at least I hope. So let’s get started and dive in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oq1WosxCfpi8N8tIRhSlWQ.png" /><figcaption>He meant Monte Cristo</figcaption></figure><h3>Table of Contents</h3><ul><li><a href="https://medium.com/p/1c96572a1401#48f5">Seven Bridges of Königsberg</a></li><li>Graph representation: Intro</li><li><a href="https://medium.com/p/1c96572a1401#0374">Intro to Graph representation and binary trees (Airbnb example)</a></li><li><a href="https://medium.com/p/1c96572a1401#fb0c">Graph representation: Outro</a></li><li><a href="https://medium.com/p/1c96572a1401#0cd4">Twitter example: tweet delivery problem</a></li><li><a href="https://medium.com/p/1c96572a1401#fb0c">Graph Algorithms: intro</a></li><li><a href="https://medium.com/p/1c96572a1401#cdde">Netflix and Amazon: inverted index example</a></li><li><a href="https://medium.com/p/1c96572a1401#45f6">Traversals: DFS and BFS</a></li><li><a href="https://medium.com/p/1c96572a1401#aa4d">Uber and the shortest path problem (Dijkstra’s algorithm)</a></li></ul><h3>Seven Bridges of Königsberg</h3><p>Let’s start with something that I used to regularly encounter in graph theory books that discuss “the origins of graph theory”, the <a href="https://en.wikipedia.org/wiki/Seven_Bridges_of_K%C3%B6nigsberg">Seven Bridges of Königsberg</a> (not really sure, but you can pronounce it as “qyonigsberg”). There were seven bridges in <a href="https://en.wikipedia.org/wiki/Kaliningrad">Kaliningrad</a>, connecting two big islands surrounded by the Pregolya river and two portions of mainlands divided by the same river.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yiwa1Lzpj6XHAXW3G9KcqA.png" /><figcaption><a href="https://www.google.com.au/maps/@54.7066964,20.5100082,16z">Our area of interest</a></figcaption></figure><p>In the 18th century this was called Königsberg (part of Prussia) and the area above had a lot more bridges. The problem or just a brain teaser with Königsberg’s bridges was to be able to walk through the city by crossing all the seven bridges only once. They didn’t have an internet connection at that time, so it should have been entertaining. Here’s the illustrated view of the seven bridges of Königsberg in 18th century.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_8_S3LGba5fYlF9epPXPAA.png" /><figcaption>Seven bridges of Königsberg</figcaption></figure><p>Try it. See if you can walk through the city by crossing each bridge only once.</p><ul><li>There should not be any uncrossed bridge(s).</li><li>Each bridge must not be crossed more than once.</li></ul><p>If you are familiar with this problem, you know that it’s impossible to do it. Although you were trying hard enough and you may try even harder now, you’ll eventually give up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*c3Vl36-jIeBzQ_rsNYml5A.jpeg" /><figcaption>Leonhard Euler (photo from Wikipedia)</figcaption></figure><p>Sometimes it’s reasonable to give up fast. That’s how Euler solved this problem - he gave up pretty soon. Instead of trying to solve it, he adopted a different approach of trying to prove that it’s not possible to walk through the city by crossing each bridge one and only time.</p><p>Let’s try to understand how Euler was thinking and how he came up with the solution (if there isn’t a solution, it still needs a proof). That is a real challenge here, because walking through the thought process of such a venerable mathematician is kind of dishonorable. (Venerable so much that <a href="https://www.amazon.com/Concrete-Mathematics-Foundation-Computer-Science/dp/0201558025/">Knuth and friends dedicated their book</a> to <a href="https://en.wikipedia.org/wiki/Leonhard_Euler">Leonhard Euler</a>). We rather will pretend to “think like Euler”. Let’s start with picturing the impossible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RPIPDVcZbWM0hy519YoZIA.png" /></figure><p>There are four distinct places, two islands and two parts of mainland. And seven bridges. It’s interesting to find out if there is any pattern regarding the number of bridges connected to islands or mainland (we will use the term “land” to refer to the four distinct places).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TQzVW18ZSpYIuOFY5ZJJJg.png" /><figcaption>Number of bridges</figcaption></figure><p>At a first glance, there seems to be some sort of a pattern. There are an odd number of bridges connected to each land. If you have to cross each bridge once, then you can enter a land and leave it if it has 2 bridges.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*jDQ0LcOdE1Ln3_27yVcnJg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*tqshIPv13IkTZIZaFIej_Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*Vs7ZeH7lHhAAXGLXH2Lyhw.png" /><figcaption>Examples of 2 bridge lands</figcaption></figure><p>It’s easy to see in the illustrations above that if you enter a land by crossing one bridge, you can always leave the land by crossing its second bridge. Whenever a third bridge appears, you won’t be able to leave a land once you enter it by crossing all its bridges. If you try to generalize this reasoning for a single piece of land, you’ll be able to show that, in case of an even number of bridges it’s always possible to leave the land and in case of an odd number of bridges it isn’t. Try it in your mind!</p><p>Let’s add a new bridge to see how the number of overall connected bridges changes and whether it solves the problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*olODXmFJsEj28jF70Sg9dw.png" /><figcaption>Notice the new bridge</figcaption></figure><p>Now that we have two even (4 and 4) and two odd (3 and 5) number of bridges connecting the four pieces of land, let’s draw a new route with the addition of this new bridge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0tIgvHoB7uGpedZx1ZnLug.png" /><figcaption>Wow</figcaption></figure><p>We saw that the number of even and odd number of bridges played a role in determining if the solution was possible. Here’s a question. Does the number of bridges solve the problem? Should it be even all the time? Turns out that it’s <strong>not</strong> the case. That’s what Euler did. He found a way to show that the number of bridges matter. And more interestingly, the number of pieces of <strong>land</strong> with an odd number of connected bridges also matters. That’s when Euler started to “convert” lands and bridges into something we know as graphs. Here’s how a graph representing the Königsberg bridges problem could look like (note that our “temporarily” added bridge isn’t there).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DZ0h0t88ZtzLNQhgalPztg.png" /><figcaption>Lines are a bit twisty</figcaption></figure><p>One important thing to note is the generalization/abstraction of a problem. Whenever you solve a specific problem, the most important thing is to generalize the solution for similar problems. In this particular case, Euler’s task was to generalize the bridge crossing problem to be able to solve similar problems in the future, i.e. for all the bridges in the world. Visualization also helps to view the problem at a different angle. The following graphs are all various representations of the same Königsberg bridge problem shown above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h8-Y7kfLY81IeZ61y6RhPA.png" /></figure><p>So yes, visually graphs are a good choice for picturing problems. But now we need to find out how the Königsberg problem can be solved using graphs. Pay attention to the number of lines coming out of each circle. And yes, let’s name them as seasoned professionals would do, from now on we will call circles, <strong>vertices</strong> and the lines connecting them, <strong>edges</strong>. You might’ve seen letter notations, <strong>V</strong> for (vendetta?) vertex, <strong>E</strong> for edge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UlIW_fTvf-URBTJHFU-mDg.png" /></figure><p>The next important thing is the so-called <strong>degree</strong> of a <strong>vertex</strong>, the number of edges <strong>incident</strong> connected to the vertex. In our example above, the number of bridges connected to lands can be expressed as degrees of the graph vertex.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ESq5g9Vi988AHHXTA1cfLw.png" /></figure><p>In his endeavor Euler showed that the possibility of a walk through graph (city) traversing each edge (bridge) one and only one time is strictly dependent on the degrees of vertices (lands). The path consisting of such edges called (in his honor) an Euler path. The length of an Euler path is the number of edges. Get ready for some strict language. 😃</p><blockquote>An Euler path of a finite undirected graph G(V, E) is a path such that every edge of G appears on it once. If G has an Euler path, then it is called an Euler graph. [1]</blockquote><blockquote><strong>Theorem</strong>. A finite undirected connected graph is an Euler graph if and only if <strong>exactly two</strong> vertices are of <strong>odd degree</strong> or <strong>all vertices</strong> are of <strong>even degree</strong>. In the latter case, every Euler path of the graph is a circuit, and in the former case, none is. [1]</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v-TkQFTU_sNzgKJiyDkkwA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mq6Gk_irYP3jwEIk33apqA.png" /><figcaption>Exactly two vertices have an odd degree in the illustration at the left, and all vertices are of an odd degree in illustration at the right</figcaption></figure><p><em>I used “Euler path” instead of “Eulerian path” just to be consistent with the referenced books [1] definition. If you know someone who differentiates Euler path and Eulerian path, and Euler graph and Eulerian graph, let them know to leave a comment.</em></p><p>First of all, let’s clarify the new terms in the above definition and theorem.</p><ul><li><strong>Undirected graph</strong> - a graph that doesn’t have a particular direction for edges.</li><li><strong>Directed graph</strong> - a graph in which edges have a particular direction.</li><li><strong>Connected graph</strong> - a graph where there is no unreachable vertex. There must be a path between every pair of vertices.</li><li><strong>Disconnected graph</strong> - a graph where there are unreachable vertices. There is not a path between every pair of vertices.</li><li><strong>Finite graph</strong> - a graph with a finite number of nodes and edges.</li><li><strong>Infinite graph</strong> - a graph where an end of the graph in a particular direction(s) extends to infinity.</li></ul><p>We’ll discuss some of these terms in the coming paragraphs.</p><p>Graphs can be directed and undirected, and that’s one of the interesting properties of graphs. You must’ve seen a popular Facebook vs Twitter example for directed and undirected graphs. A Facebook friendship relation may be easily represented as an undirected graph, because if Alice is a friend with Bob, then Bob must be a friend with Alice, too. There is no direction, both are friends with each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NsSbLC2ssMmNIUTBl3jrnQ.png" /><figcaption>Undirected Graph</figcaption></figure><p>Also note the vertex labeled as “Patrick”, it is kind of special (he’s got no friends), as it doesn’t have any incident edges. It is still a part of the graph, but in this case we will say that this graph is not connected, it is a <strong>disconnected graph </strong>(same goes with “John”, “Ashot” and “Beth” as they are interconnected with each other but separated from others)<strong>. </strong>In a <strong>connected</strong> graph there is no unreachable vertex, there must be a path between every pair of vertices.</p><p>Contrary to the Facebook example, if Alice follows Bob on Twitter, that doesn’t require Bob to follow Alice back. So a “follow” relation must have a direction indicator, showing which vertex (user) has a directed edge (follows) to the other vertex.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NogzJ2ZbrTrwh43ph-XAIQ.png" /></figure><p>Now, knowing what is a <strong>finite</strong> <strong>connected</strong> <strong>undirected</strong> graph, let’s get back to Euler’s graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h_S6hGd0Y1uDl9Pltn8QYw.png" /></figure><p>So why did we discuss Königsberg bridges problem and Euler graphs in the first place? Well, it’s not so boring and by investigating the problem and foregoing solution we touched the elements behind graphs (vertex, edge, directed, undirected) avoiding a dry theoretical approach. And no, we are not done with Euler graphs and the problem above, yet. 😶</p><p>We should now move on to the computer representation of graphs as that is the topic of interest for us programmers. By representing a graph in a computer program, we will be able to devise an algorithm for tracing graph path(s), and therefore find out if it is an Euler path. Before that, try to think of a good application for an Euler graph (besides fiddling around with bridges).</p><h3>Graph representation: Intro</h3><p>Now this is quite a tedious task, so be patient. Remember the fight between Arrays and Linked Lists? Use arrays if you need fast element access, use lists if you need fast element insertion/deletion, etc. I hardly believe you ever struggled with something like “how to represent lists”. Well, in case of graphs the actual representation is really bothering, because first you should decide how exactly are you going to represent a graph. And believe me, you are not going to like this. Adjacency list, adjacency matrix, maybe edge lists? Toss a coin.</p><p>You should have tossed hard, because we are starting with a tree. You must have seen a binary tree (or BT for short) at least once (the following is not a binary <strong>search</strong> tree).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xWoN44k1_pdTG8PwZeutxw.png" /><figcaption>Just a sample</figcaption></figure><p>Just because it consists of vertices and edges, it’s a graph. You also may recall how most commonly a binary tree is represented (at least in textbooks).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53aae7ddbd72868c01a72cad737e5c43/href">https://medium.com/media/53aae7ddbd72868c01a72cad737e5c43/href</a></iframe><p>It might seem too basic for people who are already familiar with binary trees, but I still have to illustrate it to make sure we are on the same page (note that we are still dealing with pseudocode).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ac1c0208c644f4dde7546f35a1bf6a1/href">https://medium.com/media/1ac1c0208c644f4dde7546f35a1bf6a1/href</a></iframe><p>If you are new to trees, read the pseudocode above carefully, then follow the steps in the illustration below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qGSs9H5TJrkC226E1Tr5bA.png" /><figcaption>Colors are just for bright visualization</figcaption></figure><p>While a binary tree is a simple “collection” of nodes, each of which has left and right child nodes. A binary search tree is much more useful as it applies one simple rule which allows fast key lookups. Binary search trees (BST) keep their keys in sorted order. You are free to implement your BT with any rule you want (although it might change its name based on the rule, for instance, min-heap or max-heap). The most important expectation for a BST is that it satisfies the <strong>binary search</strong> property (that’s where the name comes from). Each node’s key must be <strong>greater than</strong> any key in its left sub-tree and <strong>less than</strong> any key in its right sub-tree.</p><p>I’d like to point out a very interesting point regarding the statement “greater than” that’s crucial to understand how BST’s function. Whenever you change the property to “greater than or equal”, your BST will be able to save duplicate keys when inserting new nodes, otherwise it will keep only nodes with unique keys. You can find really good articles on the web about binary search trees. We won’t be providing a full implementation of a binary search tree, but for the sake of consistency, we’ll illustrate a simple binary search tree here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gb8tsJ_MOTcIvZlYC2HkmQ.png" /></figure><h3>Intro to Graph representation and binary trees (Airbnb example)</h3><p>Trees are very useful data structures. You might not have implemented a tree from scratch in your projects. But you’ve probably used them even without noticing. Let’s look at an artificial yet valuable example and try to answer the “why” question, “Why use a binary search tree in the first place”.</p><p>As you’ve noticed, there is a “search” in binary search tree. So basically, everything that needs a fast lookup, <strong>should</strong> be placed in a binary search tree. “Should” doesn’t mean must, the most important thing to keep in mind in programming is to solve a problem with proper tools. There are tons of cases where a simple linked list with its O(N) lookup might be more preferable than a BST with its O(logN) lookup.</p><p>Typically we would use a library implementation of a BST, <a href="https://www.amazon.com/Expert-proficient-programmer-learning-practices/dp/1838552650/">most likely std::set or std::map</a> in C++. However in this tutorial we are free to <strong>reinvent</strong> our own wheel. BSTs are implemented in almost any general-purpose programming language library. You can find them in the corresponding documentation of your favorite language. Approaching a “real-life example”, here’s the problem we’ll try to tackle - Airbnb Home Search.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2WwX3k9JJHeLX2d8hYz39Q.png" /><figcaption>A glimpse on Airbnb Homes Search</figcaption></figure><p>How do we search for homes based on some query with a bunch of filters as fast as possible. This is a hard task. It becomes harder if we consider that Airbnb stores <a href="https://press.atairbnb.com/app/uploads/2017/08/4-Million-Listings-Announcement-1.pdf">4 millions listings</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-FXZCO9EfVU5cpt-UbsK3Q.png" /></figure><p>So when users search for homes, there is a chance that they might “touch” 4 million records stored in the database. Sure the results are limited to the “top listings” shown on the website’s home page and a user almost is never curious “enough” to view millions of listings. I don’t have any analytics regarding Airbnb, but we can use a powerful tool in programming called “assumptions”. So we will assume that a single user finds a good home by viewing at most ~1K homes.</p><p>The most important factor here is the number of real-time users, as it makes a difference in data structures and database(s) choices and the project architecture overall. As obvious as it might seem, if there are just 100 users overall, then we may not bother at all.</p><p>On the contrary, if the number of users overall and real-time users in particular is far beyond the million threshold, we have to think really wisely about each decision. “Each” is used exactly right, that’s why companies hire the best while striving for excellence in service provision.</p><p>Google, Facebook, Airbnb, Netflix, Amazon, Twitter, and many others deal with huge amounts of data and the right choice to serve millions of bytes of data each second to millions of real-time users starts from hiring the right engineers. That’s why we, the programmers, struggle with these data structures, algorithms and problem solving in possible interviews, because all they need is the engineer having the ability to solve such big problems in the fastest and most efficient possible way.</p><p>So here’s a use case. A user visits the home page (we’re still talking about Airbnb) and tries to filter out homes to find the best possible fit. How would we deal with this problem? (Note that this problem is rather backend-side, so we won’t care about front-end or the network traffic or https over http or Amazon EC2 over home cluster and so on).</p><p>First of all, as we are already familiar with one of the most powerful tools in a programmers’ inventory (talking about assumptions rather than abstractions), let’s start with a few assumptions:</p><ul><li>We’re dealing with data that completely fits in the RAM.</li><li>Our RAM is big enough.</li></ul><p>Big enough to hold, hmm, how much? Well that’s a good question. How much memory will be required to store the actual data. If we are dealing with 4 million units of data (again, am assumption), and if we probably know each unit’s size, then we can easily derive the required memory size, i.e. 4M * sizeof(one_unit).</p><p>Let’s consider a “home” object and its properties. Actually, let’s consider at least those properties that we will deal with while solving our problem (a “home” is our unit). We will represent it as a <a href="https://www.amazon.com/Expert-proficient-programmer-learning-practices/dp/1838552650/">C++ structure</a> in some pseudocode. You can easily convert it to a MongoDB schema object or anything you want. We just discuss the property names and types (try to think about using bitfields or bitsets for space economy).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b6bdfc58f0d6eefaa8c4acc63fa51a0/href">https://medium.com/media/7b6bdfc58f0d6eefaa8c4acc63fa51a0/href</a></iframe><p>The above structure is not perfect (obviously) and there are many assumptions and/or incomplete parts. I just looked at Airbnb’s filters and devised property lists that should exist to satisfy search queries. It’s just an example.</p><p>Now we should calculate how many bytes in memory will take each AirbnbHome object.</p><ul><li><strong>Home name</strong> -name is a wstring to support multilingual names/titles, which means each character will take 2 bytes (we may not bother with character size if we would use other language, but in C++ char is 1-byte character and wchar is 2-byte character). A quick look at Airbnb’s listings allows us to assume that the name of a home should take up to 100 characters (though mostly it is around 50, rather than 100), we’ll assume 100 characters as a maximum value, which leads to ~200 bytes of memory. uint is 4 bytes, uchar is 1 byte, ushort is 2 bytes (again, in our assumptions).</li><li><strong>Photos</strong> - Photos are residing within some storage service, like Amazon S3 (as far as I know, this assumption is most likely to be true for Airbnb, but again, Amazon S3 is just an assumption)</li><li><strong>Photo URLs</strong> - We have those photo URLs, and considering the fact that there is no standard size limit on the URLs, but there is in fact a well-known limit of <strong>2083</strong> characters, we‘ll take it as a max size of any URL. So taking into account that each home has 5 photos in average, it would take up to ~10Kb.</li><li><strong>Photo IDs</strong> - Let’s have a rethink about this. Usually storage services serve content with the same base URLs, like http(s)://s3.amazonaws.com/&lt;bucket&gt;/&lt;object&gt;, i.e. there is a common pattern for constructing URLs and we need to store only the actual photo ID. Let’s say we use some unique ID generator, which returns a 20 byte unique string ID where photo objects and the URL pattern for particular photo looks like https://s3.amazonaws.com/some-know-bucket/&lt;unique-photo-id&gt;. This gives us good space efficiency, so for storing string IDs of five photos we will need only 100 bytes of memory.</li><li><strong>Host ID</strong> - The same “trick” (above) could be done with the host_id, i.e. the user ID who hosts the home, takes 20 bytes of memory (<em>actually we could just use integer IDs for users, but considering that some DB systems like MongoDB have rather specific unique ID generator, we’re assuming a 20 byte length string ID as some “median” value which fits into almost any DB system with a little change. Mongo’s ID length is 24 bytes</em>). And finally, we’ll take a bitset of up to 32 bits in size as a 4 bytes object and a bitset of size between 32 and 64 bits, as a 8 byte object. Mind the assumptions. We used bitset in this example for any property that expresses an enum, but is able to take more than one value, in other words a kind of multiple choice checkbox.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YcTk591Iy-MzQte5jnXfRg.png" /><figcaption>Airbnb House Amenities</figcaption></figure><p><strong>Amenities</strong> - Each Airbnb home keeps a list of available amenities, e.g. “iron”, “washer”, “tv”, “wifi”, “hangers”, “smoke detector” and even “laptop friendly workspace” and so on. There might be more than 20 amenities, we stick to the 20 just because it’s the number of filterable amenities on the Airbnb filters page. Bitset saves us some good space, if we keep proper ordering for amenities. For instance, if a home has all above mentioned amenities (see checked ones in the screenshot), we will just set a bit at corresponding position in the bitset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lj3oDNQ70FdpOT_lKfdD2w.png" /><figcaption>Bitset allows to save 20 different values using just 20 bits</figcaption></figure><p>For example, checking if a home has a “washer”:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22eaf78f74af2761568ab3e47a55a4f1/href">https://medium.com/media/22eaf78f74af2761568ab3e47a55a4f1/href</a></iframe><p>Or a little more professionally:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a129659839e3dee564ed9fb0e3d6887/href">https://medium.com/media/9a129659839e3dee564ed9fb0e3d6887/href</a></iframe><p>You can improve the code as much as you want (and fix compile errors). We just wanted to emphasize the idea behind bitsets in this problem context.</p><ul><li><strong>House rules, Home Type</strong> - The same idea (that we implemented for the amenities field) goes with “house rules”, “home type” and others.</li><li><strong>Country code, City name</strong> - Finally, the country code and city name. As mentioned in the comments of the code above (see remarks), we won’t store latitude and longitude to avoid geo-spatial queries (<em>a subject of another article</em>). Instead, we save country code and city name to narrow down the search by a location (omitting streets for the sake of simplicity, please forgive me). <a href="https://en.wikipedia.org/wiki/Country_code">Country code</a> could be represented as 2 characters, 3 characters or 3 digits, we’ll save a numeric representation and will use an ushort for it. (Un)fortunately there are many more cities than countries, so we can’t use a “city code” (though we can make one for internal use). Instead we’ll store actual city name, preserving 50 bytes in average for a city name and for super-specific cases like <a href="https://en.wikipedia.org/wiki/Taumatawhakatangihangakoauauotamateaturipukakapikimaungahoronukupokaiwhenuakitanatahu">Taumatawhakatangihangakoauauotamateaturipukakapikimaungahoronukupokaiwhenuakitanatahu</a> (85 letter city). We better use an additional boolean variable which indicates that this is that specific super-long city (don’t try to pronounce it). So, keeping in mind the memory overhead of strings and vectors. We’ll add an additional 32 bytes (just in case) to the final size of the struct. We also will assume that we work on a 64-bit system, although we chose very compact values for int and short.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/083d9e2d4f5ecde3bc0fed0f0af2b620/href">https://medium.com/media/083d9e2d4f5ecde3bc0fed0f0af2b620/href</a></iframe><p>So, <strong>420</strong>+ bytes with an overhead of <strong>32</strong> bytes, <strong>452</strong> bytes and considering the fact that some of you might just be obsessed with the aligning factor, let’s round up it to <strong>500 bytes</strong>. So each “home” object takes up to 500 bytes, and for all home listings (<em>there could be some confusing moments with the listings count and actual home count, just let me know if I got something wrong</em>), 500 bytes * 4 million = 1.86GB ~ <strong>2GB</strong>. Seems plausible. We made many assumptions while constructing the struct, making it cheaper to save in memory, I really expected much more than 2 Gigabytes and if I did a mistake in calculations, let me know. Anyway, moving forward, so whatever we gonna do with this data, we will need at least 2 GB of memory. If you got bored, deal with it. We are just starting.</p><p>Now the hardest part of the task. Choosing the right data structure for this problem (filter the listings as efficiently as possible) is not the hardest task. The hardest task is (for me) to search listings by a bunch of filters. If there would be just one search key (just one filter) we would easily solve it. Suppose the only thing users care is the price, so all we need is to find AirbnbHome objects with prices falling in the provided range. If we’ll use a binary search tree for that, here’s how it might look.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6cm5jXJsovsulzqUQNo2ww.png" /></figure><p>If you imagine all 4 millions objects, this tree grows very very big. By the way, the memory overhead grows as well, just because we used a BST to store objects. As each parent tree node has two additional pointers to its left and right child it adds up to 8 additional bytes for each child pointer (assuming a 64-bit system). For 4 million nodes it sums up to <strong>~62 Mb</strong>, which in comparison to 2Gb of object data looks quite small, though it is not something that we can “omit” easily.</p><p>The tree in the last illustration so far shows that any item can be easily found in O(logN) complexity. If you aren’t familiar or are not sure enough to chit-chat in big-ohs, we’ll clarify it below, otherwise skip the complexity subsection.</p><p><strong>Algorithmic complexity</strong> - Let’s make this quick as there will be a long and detailed explanation in an upcoming article: “Algorithmic Complexity and Software Performance: The Missing Manual”. For most of the cases finding the big O complexity for an algorithm is somewhat easy. First thing to note is that we always consider the worst case, i.e. the maximum number of operations that an algorithm does to produce a positive outcome (to solve the problem).</p><p>Suppose an array has 100 elements in an unsorted order. How many comparisons would it take to find an element (also taking into account that the required element could be missing)? It will take up to 100 comparisons as we should compare each element’s value with the value we are looking for. And despite the fact that the element might be the first element in the array (leading to a single comparison), we will consider only the worst possible case (element is either missing or is residing at the last position of the array).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ty0mOl97RJvfnECai3VxqQ.png" /></figure><p>The point of “calculating” algorithmic complexity is finding a <strong>dependency</strong> between the <strong>number of operations</strong> and the<strong> size of input</strong>, for instance the array above had 100 elements and the number of operations were also 100, if the number of array elements (its input) will increase to 1423, the number of operations to find any element will also increase to 1423 (the worst case). So the thin line between input and number of operations is clear in this case, it is so-called <strong>linear</strong>, the number of operations grows as much as grows array’s input. Growth. That’s the key point in complexity, we say that searching for an element in an unsorted array takes O(N) time to emphasize that the process of finding it will take up to N operations (or even up to N operations times some constant value such as 3N). On the other hand, accessing any element in an array takes a constant time, i.e. O(1). That’s because of an array’s structure. It’s a contiguous data structure, and holds elements of the same type (mind JS arrays), so “jumping” to a particular element requires only calculating its relative position to the array’s first element.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I8cUohRCKnF8FUznv6-dEA.png" /></figure><p>One thing is very clear. A binary search tree keeps its nodes in sorted order. So what would be the algorithmic complexity of searching an element in a binary search tree? We should calculate the number of operations required to find an element (in the worst case).</p><p>Look at the illustration above. When starting our search at the root, the first comparison may lead to three cases,</p><ol><li>The node is found.</li><li>The comparison continues to node’s left sub-tree if the required element is less than the node’s value</li><li>The comparison continues to the node’s right sub-tree if the value we search for is greater than the node’s value.</li></ol><p>At each step we reduce the size of nodes needed to be considered by half. The number of operations (i.e. comparisons) needed to find an element in the BST equals the height of the tree. The height of a tree is the number of nodes on the longest path. In this case it’s 4. And the height is [base 2] logN + 1, as shown. So the complexity of search is O(logN + 1) = O(logN). This means that searching something in 4 million nodes requires log4000000 = ~<strong>22</strong> comparisons in the worst case.</p><p><strong>Back to the tree</strong> - Element access time in a binary search tree is O(logN). Why not use hashtables? Hashtables have constant access time, which makes it reasonable to use hashtables almost everywhere.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*MoSZx3_lIQtpkHUQg5A0iw.png" /></figure><p>In this problem we must take into account an important requirement. We must be able to make range searches, e.g. homes with prices from $80 to $162. In case of a BST, it’s easy to get all the nodes in a range just by doing an inorder traversal of the tree and keeping a counter. For a hashtable it is somewhat expensive which makes it reasonable to stick with BSTs in this case.</p><p>Though there is another spot, which leads us to rethink hashtables. The density. Prices won’t go up “forever”, most of the homes reside at the same price range. Look at the screenshot, the histogram shows us the real picture of the prices, millions of homes are in the same range (+/- $18 - $212), they have the same average price. Simple arrays may play a good role. Assuming the index of an array as the price and the value as the list of homes, we might access any price range in constant time (well, almost constant). Here’s how it looks (way abstract):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GWjOQqisi3Hi5f3Ic5P6_Q.png" /></figure><p>Just like a hashtable, we are accessing each set of homes by its price. All homes having the same price are grouped under a separate BST. It will also save us some space if we store home IDs instead of the whole object defined above (the AirbnbHome struct). The most possible scenario is to save all homes full objects in a hashtable mapping home ID to home full object and storing another hashtable (or better, an array), which maps prices with homes IDs.</p><p>So when users request a price range, we fetch home IDs from the price table, cut the results to a fixed size (i.e. the pagination, usually around 10 - 30 items are shown on one page), fetch the full home objects using each home ID.</p><p>Just keep another thing in mind (think of it in the background). Balancing is crucial for a BST, because it’s the only guarantee of having tree operations done in O(logN). The problem of unbalanced BST is obvious when you insert elements in sorted order. Eventually, the tree becomes just a linked list, which obviously leads to linear-time operations. Forget this for now, suppose all our trees are perfectly balanced. Take a look at the illustration above once again. Each array element represents a big tree. What if we change the illustration to something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CPvsz7H8IuGrFdoa4USKsQ.png" /><figcaption>More like a graph</figcaption></figure><p>It resembles a “more realistic” graph. This illustration represents the most disguised data structures and graphs, which takes us to the next section.</p><h3>Graph representation: Outro</h3><p>The bad news about graphs is that there isn’t a single definition for the graph representation. That’s why you can’t find a std::graph in the library. We already had a chance to represent a “special” graph called BST. The point is, tree is a graph, but graph is not a tree. The last illustration shows us that we have a lot of trees under a single abstraction, “prices vs homes” and some of the vertices “differ” in their type, prices are graph nodes having only the price value and refer to the whole tree of home IDs (home vertices) that satisfy the particular price. It is much like a hybrid data structure, than a simple graph that we’re used to seeing in textbook examples.</p><p>That’s the key point in graph representation, there isn’t a fixed and “de jure” structure for graph representation (unlike BSTs with their specified node-based representation with left/right child pointers, though you can represent a BST with a single array). You can represent a graph in the most convenient way you wish (most convenient to particular problem), the main thing is that you “see” it as a graph. And by “seeing a graph” we mean applying algorithms that are specific to graphs.</p><p>What about an N-ary tree, it is more likely to resemble a graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WAGdBjYglJ73UEpOrUh1BA.png" /></figure><p>And the first thing that comes into mind to represent an N-ary tree node is something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79f48cf78a1a8e787ac6fcf756651a12/href">https://medium.com/media/79f48cf78a1a8e787ac6fcf756651a12/href</a></iframe><p>This structure represents just a single node of a tree. The full tree looks more like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a860978d734c22164210bf6eb7f56adc/href">https://medium.com/media/a860978d734c22164210bf6eb7f56adc/href</a></iframe><p>This class is an abstraction around a single tree node named root_ . That’s all we need to build a tree of any size. That’s the starting point of the tree. For adding a new tree node we need to allocate a memory to it and add that node to the root of the tree.</p><p>A graph is much like an N-ary tree, with a slight difference. Try to spot it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cu05NUgY1SBx3ZzeH8SLgw.png" /></figure><p>Is this a graph? No. I mean yes, but it’s the same N-ary tree from the previous illustration, just a little rotated. As a rule of a thumb, whenever you see a tree (even if it is an apple tree, lemon tree or binary search tree), you can be sure that it is also a graph. So, devising a structure for a graph node (graph vertex), we can come up with the same structure:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9119087f1c12d3415bd0c3328416ab65/href">https://medium.com/media/9119087f1c12d3415bd0c3328416ab65/href</a></iframe><p>Is this enough to construct a graph? Well, no. And here’s why. Look at these two graphs from previous illustrations, find a difference:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CPvsz7H8IuGrFdoa4USKsQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cu05NUgY1SBx3ZzeH8SLgw.png" /><figcaption>Both are graphs</figcaption></figure><p>The graph in the illustration at the left side has no single point to “enter” (it’s rather a forest than a single tree), in the contrary, the graph in the right illustration doesn’t have unreachable vertices. Sounds familiar.</p><blockquote>A graph is <strong>connected</strong> when there is a path between every pair of vertices. [<a href="https://en.wikipedia.org/wiki/Connectivity_(graph_theory)">Wikipedia</a>]</blockquote><p>Obviously, there isn’t a path between every pair of vertices for the “prices vs homes” graph (if it isn’t obvious from the illustration, just assume that prices are not connected with each other). As much as it’s just an example to show that we aren’t able to construct a graph with a single GraphNode struct, there are cases that we have to deal with disconnected graphs like this. Take a look at this class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/538b05968609aa8d01e5d253ee10cf2f/href">https://medium.com/media/538b05968609aa8d01e5d253ee10cf2f/href</a></iframe><p>Just like an N-ary tree is built around a single node (the root node), a connected graph also can be built around a root node. It’s said that trees are “rooted”, i.e. they have a starting point. A connected graph can be represented as a rooted tree (with a couple of more properties), it’s already obvious, but keep in mind that the actual representation may differ from algorithm to algorithm, from problem to problem even for a connected graph. However, considering node-based nature of graphs, a disconnected graph can be represented like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a1662b7cbfa9a1bcb569e174493ce0e/href">https://medium.com/media/7a1662b7cbfa9a1bcb569e174493ce0e/href</a></iframe><p>For graph traversals like DFS/BFS it’s natural to use a tree-like representation. Helps a lot. However, cases like efficient path tracing require a different representation. Remember Euler’s graph? To track down a graph’s “eulerness”, we should trace an Euler path within it. That means visiting all vertices by traversing each edge only once, and when the tracing finishes and we have untraversed edges, then the graph doesn’t have an Euler path, and therefore is not an Euler graph.</p><p>There is even faster method, we can check the degrees of vertices (suppose each vertex stores its degree) and just as the definition says, if a graph has vertices of odd degree and there aren’t exactly two of them, then it is not an Euler graph. The complexity of such a check is O(|V|), where |V| is the number of graph vertices. We can track down odd/even degrees while inserting new edges to increase odd/even degree checks to O(1). Lightning fast. Never mind, we’re just going to trace a graph, that’s it. Below is both the representation of a graph and the Trace() function returning a path.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0bca1e8a3b9d7f1d6066c9cafcdba082/href">https://medium.com/media/0bca1e8a3b9d7f1d6066c9cafcdba082/href</a></iframe><p>Mind the bugs, bugs are everywhere. This code contains a lot of assumptions, for instance, the labeling, so by a vertex we understand a string label. Sure you can easily update it to be anything you want. Doesn’t matter in the context of this example. Next, the naming. As mentioned in the comments, VELOGraph is for Vertex Edge Label Only Graph (I made this up). The point is, this graph representation contains a table for mapping a vertex label with edges incident to that vertex, and a list of edges containing a pair of vertices (connected by a particular edge) and a flag which is used only by the Trace() function. Take a look at the Trace() function implementation. It uses edge’s flag to mark an already traversed edge (flags should be reset after any Trace() call).</p><h3>Twitter Example: Tweet Delivery Problem</h3><p>Here’s another representation called an adjacency matrix, which could be useful in directed graphs, like one we used for Twitter follower graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NogzJ2ZbrTrwh43ph-XAIQ.png" /><figcaption>Directed graph</figcaption></figure><p>There are 8 vertices in this Twitter example. So all we need to represent this graph is a |V|x|V| square matrix (|V| number of rows and |V| number of columns). If there is a directed edge from <strong>v</strong> to <strong>u</strong>, then matrix’s [v][u] is true, otherwise it’s false.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s--uEeTmQg9f8LhHHGFKtA.png" /><figcaption>Twitter’s example</figcaption></figure><p>As you can see, this matrix is way too sparse, its trade off is the fast access. To see if Patrick follows Sponge Bob, we should just check the value of matrix[&quot;Patrick&quot;][&quot;Sponge Bob&quot;]. To get the list of Ann’s followers, we just process the entire “Ann” column (title is in yellow). To find who are being followed (sounds strange) by Sponge Bob, we process the entire row “Sponge Bob”. Adjacency matrix could be used for undirected graphs as well, and instead of settings 1’s if a there is an edge from <strong>v</strong> to <strong>u</strong>, we should set both values to 1, e.g. adj_matrix[v][u] = 1, adj_matrix[u][v] = 1. Undirected graph’s adjacency matrix is symmetric.</p><p>Note that instead of storing ones and zeroes in an adjacency matrix, we can store something “more useful”, like <strong>edge weights</strong>. One of the best examples might be a graph of places with distance information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gMt-tHRL-FeRk-P2-OYprg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zH3p8q22YGh-UfzsrJ4VDA.png" /></figure><p>The graph above represents distances between houses of Patrick, Sponge Bob and others (also known as <strong>weighted graph</strong>). We put “infinity” signs if there isn’t a direct route between vertices. That doesn’t mean that there are no routes at all, and at the same time that doesn’t mean that there must necessarily be routes. It might be defined while applying an algorithm for finding a route between vertices (there is even better way to store vertices and edges incident to it, called an incidence matrix).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mXDa1tFIZi5ohpamzVz-cQ.jpeg" /><figcaption>82000Tb. <a href="http://www.independent.co.uk/arts-entertainment/tv/news/the-simpsons-death-episode-will-be-bigger-than-game-of-thrones-9304810.html">Photo source</a></figcaption></figure><p>While adjacency matrix seemed a good use for Twitter’s followes graph, keeping a square matrix for nearly 300 million users (monthly active users) takes 300 * 300 * 1 bytes (storing boolean values). That is, ~82000 Tb (Terabytes), which is 1024 * 82000 Gb. Well, don’t know about your home cluster, my laptop doesn’t have so much RAM. Bitsets? A <a href="https://github.com/vardanator/ultron/blob/master/src/arrays/bitboard.h">BitBoard</a> could help us a little, reducing the required size to ~10000 Tb. Still way too big. As mentioned above, an adjacency matrix is too sparse. It forces us to use more space than actually needed. That’s why using a list of edges incident to vertices may be useful. The point is, an adjacency matrix allows us to keep both “follows” and “doesn’t follow” information, while all we need is to know information about the followes, something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jtt7z3iHFr7xSFSKX95DTA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qqTFXXc44_2aqx4dEhPkQw.png" /><figcaption>Adjacency matrix vs adjacency list</figcaption></figure><p>The illustration at the right side is called an <a href="https://en.wikipedia.org/wiki/Adjacency_list">adjacency list</a>. Each list describes the set of neighbors of a vertex in the graph. By the way, the actual implementation of the graph representation as an adjacency list, again, differs (ridiculous facts). In the illustration, we highlighted a hashtable usage, which is reasonable, as the access of any vertex will be O(1), and for the list of neighbor vertices we didn’t mention the exact data structure, deviating from linked lists to vectors. Choice is yours.</p><p>The point is, to find out whether Patrick does follow Liz, we should access the hashtable (constant time) and go through all items in the list comparing each element with “Liz” element (linear time). Linear time isn’t that bad at this point, because we have to loop over only a fixed amount of vertices adjacent to “Patrick”. What about the space complexity, is it ok to use at Twitter? Well, we need at least 300 million hashtable records, each of which points to a vector (choosing vector to avoid memory overhead of linked lists’ left/right pointers) containing, how much? No stats here, found just an average number of twitter followers, 707 (googled).</p><p>So if we consider that each hashtable record points to an array of 707 user IDs (each weighing 8 byte), and let’s assume that hashtable’s overhead is only its keys, which are again, user ids, so the hashtable itself takes 300 million * 8 bytes. Overall, we have 300 million * 8 bytes for hashtable + 707 * 8 bytes for each hashtable key, that is 300 million * 8 * 707 * 8 bytes = <strong>~12 Tb</strong>. Well, can’t say that feels better, but yes, feels much better than 10,000 Tb.</p><p>Honestly, I don’t know whether this 12Tb is a reasonable number. But considering the fact that I’m spending around $30 on a dedicated server machine with 32 Gb of RAM, then, storing (sharded) 12 Tb requires at least 385 such servers, plus a couple of control servers (for data distribution control) rounds up to 400. So it will cost me $12K (monthly).</p><p>Well, considering the fact that the data should be replicated, and that something always can go wrong, we’ll triple the number of servers and then again, add some control servers, let’s say we need at least 1500 servers, which will cost us $45K monthly. Well, definitely not good for me as I hardly can keep one server, but seems okay for Twitter (it’s really nothing compared to real Twitter servers). Let’s assume it is really okay for Twitter.</p><p>Now, are we okay here? Not yet, that was just the data regarding the followers. What is the main thing in Twitter? I mean, technically, what is its biggest problem? You won’t be alone if you say it’s the fast delivery of tweets. I will definitely second that. And not fast, but lightning fast. Say Patrick tweeted something about his thoughts on food, all his followers should receive that very tweet in a reasonable time. How long will it take? We are free of making any assumption here, and use any abstractions we want, but we are interested in the real world production systems, so, let’s dig. Here’s what’s typically happens when someone tweets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rxZGqG1AW6lSlhIl9sQuGA.png" /></figure><p>Again, don’t know much about how long it takes for one tweet to reach all followers, but publicly available statistics tell us that there are about 500 million daily tweets. Daily! 😮</p><p>So the process above happens 500 million times every day. I can’t really find anything on tweet delivery speed. I vaguely recall something about a maximum of 5 seconds for a tweet to reach all its followers. And also note the “heavy cases”, celebrities with more than a million followers. They might tweet something about their wonderful breakfast at the beach house, but Twitter sweats much to deliver that super-useful content to millions of followers.</p><p>To solve tweet delivery problem we don’t really need the graph of followers, instead we need a graph of <strong>following</strong>. The previous graph (with a hashtable and a bunch of lists) allows us to efficiently find all users followed by any particular user. But it does not allow us to efficiently find <strong>all</strong> users who are following one particular user, for that case we have to scan all the hashtable keys. That’s why we should construct another graph, which is kind of a symmetric opposite to the one we constructed for followers. This new graph will again consist of a hashtable containing all 300 million vertices, each of which points to a list of adjacent vertices (the structure remains the same), but this time, the list of adjacent vertices will represent followers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*axs6Z0F87LcnxtHJXoNPKw.png" /></figure><p>So based on this illustration, whenever Liz tweets something, Sponge Bob and Ann must see that very tweet on their timelines. A common technique to accomplish this is by keeping separate structures for each user’s timeline. In case of Twitter’s 300+ million users, we might assume there are at least 300+ million timelines (for each user). Basically, whenever a user tweets, we should get the list of user’s followers and update their timelines (insert that same tweet into each one of them). A timeline might be represented as a linked list, or a balanced tree (tweet datetimes as node keys).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a112441177141c5c9709526c2a0e4008/href">https://medium.com/media/a112441177141c5c9709526c2a0e4008/href</a></iframe><p>This is just a basic idea we abstracted from actual timeline representation and of course, we can make the actual delivery faster if we use multithreading. This is crucial for ‘heavy cases’, because for millions of followers the ones that reside closer to the end are being processed later than the ones residing closer to the front of the list.</p><p>The following pseudocode tries to illuminate this multithreading delivery idea:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/730335f911c6b06587653a3c8955c5ae/href">https://medium.com/media/730335f911c6b06587653a3c8955c5ae/href</a></iframe><p>So whenever followers refresh their timelines, they will receive the new tweet.</p><p>It will be fair to say, that we merely touched the tip of the iceberg of real problems at Airbnb or Twitter. It takes a really long time and the hard work of really talented engineers to accomplish such great results in complex systems like Twitter, Google, Facebook, Amazon, Airbnb and others. Just keep this in mind while reading this article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*28Qw4dWbrh3kljvxOuLgjw.png" /></figure><p>The point of demonstrating Twitter’s tweet delivery problem is to embrace the usage of graphs, even though we didn’t use any graph algorithm, we just used a representation of the graph. Sure we pseudocoded a function for delivering tweets, but that is something we came up during the process of searching for a solution.</p><p>What I meant by “any graph algorithm” is any algorithm <a href="https://en.wikipedia.org/wiki/List_of_algorithms#Graph_algorithms">from this list</a>. As something big enough to make programmers cry, graph theory and graph algorithm applications are somewhat different to spot at a glimpse. We were discussing the Airbnb homes and efficient filtering before finishing with graph representations, and the main obvious thing was the inability to efficiently filter homes with more than one filter key. Is there anything that could be done using graph algorithms? Well, we can’t tell for sure, but at least we can try. What if we represent each filter as a separate vertex?</p><p>Literally each filter, even all the prices from $10 to $1000+, all city names, country codes, amenities (TV, Wi-Fi, and all others), number of adults, and each number as a separate graph vertex.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R756x_xP1VA-vlQu6lElJQ.png" /><figcaption>Excerpt of Airbnb filters</figcaption></figure><p>We can even make this set of vertices more “friendly” if we add “type” vertices too, like “Amenities” connected to all vertices representing an amenity filter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K4SFmofsfg-V2yu6zbwwXw.png" /><figcaption>Airbnb filters with types</figcaption></figure><p>Now, what if we represent Airbnb homes as vertices and then connect each home with “filter” vertex if that home supports the corresponding filter (For example, connecting “home 1” with “kitchen” if “home 1” has “kitchen” in its amenities)?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SozJ2RceNg1CA-hua1324w.png" /><figcaption>Looks messy</figcaption></figure><p>A subtle change of this illustration makes it more likely to resemble a special type of graph, called a <strong>bipartite graph</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rJDMNi0VK44XoIWIEqem-A.png" /><figcaption>Number of vertices are more than it may appear</figcaption></figure><p><em>Bipartite graph or just bigraph is a graph whose vertices can be divided into two disjoint and independent sets such that every edge connects a vertex in one set to one in other set. - </em><a href="https://en.wikipedia.org/wiki/Bipartite_graph"><em>Wikipedia</em></a>.</p><p>In our example one of the sets represents filters (we’ll denote it by F) and the other is a homes set (denoted by H). For example, if there are 100 thousand homes with the price value $62, then price vertex labeled “$62” will have 100 thousand edges incident to each homes vertices. If we measure the worst case of space complexity, i.e. each home has all the properties satisfying to all the filters, than the total amount of edges to be stored will be 70,000 * 4 million. If we represent each edge as a pair of two ids: {filter_id; home_id} and if we rethink about IDs and use a 4 byte (int) numeric id for filters and 8 byte (long) id for homes, then each edge would require at least 12 bytes. So storing 70,000 * 4 million 12 bytes values will require around 3Tb of memory. We made a small mistake in calculation, you see.</p><p>The number of filters is around 70,000 because of the 65 thousand cities active in Airbnb (<a href="https://press.atairbnb.com/fast-facts/">stats</a>). And the good news is that the same home cannot be located in more than one city. That is, our actual number of edges pairing with cities is 4 million (each home located in one city). So we’ll calculate for 70k - 65k = 5 thousand filters, that means we need 5000 * 4 million * 12 bytes of memory, which is less than 0.3 Tb. Sounds good. But what gives us this bipartite graph? Most commonly a website/mobile request will consist of several filters, for example like this:</p><pre>house_type: &quot;entire_place&quot;,<br>adults_number: 2,<br>price_range_start: 56,<br>price_range_end: 80,<br>beds_number: 2,<br>amenities: [&quot;tv&quot;, &quot;wifi&quot;, &quot;laptop friendly workspace&quot;],<br>facilities: [&quot;gym&quot;]</pre><p>And all we need is to find all the “filter vertices” above and process all the “home vertices” that are adjacent to these “filter vertices”. This takes us to a scary subject.</p><h3>Graph Algorithms: Intro</h3><p>Any processing done with graphs might be categorized as a “graph algorithm”. You literally can implement a function printing all the vertices of a graph and name it “<em>&lt;your name here&gt;’s vertex printing algorithm</em>”. Most of us are scared of the graph algorithms listed in textbooks (<a href="https://en.wikipedia.org/wiki/List_of_algorithms#Graph_algorithms">see the full list here</a>). Let’s try to apply a bipartite graph matching algorithm, such as <a href="https://en.wikipedia.org/wiki/Hopcroft%E2%80%93Karp_algorithm">Hopcroft-Karp algorithm</a> to our Airbnb homes filtering problem:</p><blockquote>Given a bipartite graph of Airbnb homes (H) and filters (F), where every element (vertex) of H can have more than one adjacent elements (vertex) of F (sharing a common edge). Find a subset of H consisting of vertices that are adjacent to vertices in a subset of F.</blockquote><p>Confusing problem definition, however we can’t be sure at this point whether Hopcroft-Karp algorithm solves our problem. But I assure you that this journey will teach us many crucial ideas behind graph algorithms. And the journey is not so short, so be patient.</p><p><em>The </em><a href="https://en.wikipedia.org/wiki/John_Hopcroft"><strong><em>Hopcroft</em></strong></a><strong><em>–</em></strong><a href="https://en.wikipedia.org/wiki/Richard_M._Karp"><strong><em>Karp</em></strong></a><strong><em> algorithm</em></strong><em> is an algorithm that takes as input, a bipartite graph and produces as output, a maximum cardinality matching - a set of as many edges as possible with the property that no two edges share an endpoint - </em><a href="https://en.wikipedia.org/wiki/Hopcroft%E2%80%93Karp_algorithm"><em>Wikipedia</em></a><em>.</em></p><p>Readers familiar with this algorithm are already aware that this doesn’t solve our problem, because matching requires that no two edges share a common vertex.</p><p>Let’s look at an example illustration, where there are just 4 filters and 8 homes (for the sake of simplicity).</p><ul><li>Homes are denoted by letters from A through H, filters are chosen randomly.</li><li>Home A has a price ($50), and 1 bed, (that’s all we got for the price).</li><li>All homes from A through H have a $50 per night price tag and 1 bed, but few of them have “Wi-Fi” and/or “TV”.</li></ul><p>So the following illustration tries to show which homes should we “return” for the request asking for homes that have all four filters available (For example, they cost $50 per night, they have 1 bed and also they have Wi-Fi and TV).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r2G1A2OoG8KeTmqImr4SXQ.png" /></figure><p>The solution to our problem requires edges with common vertices leading to distinct home vertices that are incident to the same filter subset, while Hopcroft-Karp algorithm eliminates such edges with common endpoints and produces edges incident to vertices in both subsets.</p><p>Take a look at the illustration above, all we need are homes D and G, which both satisfy to all four filter values. What we really need is to get all matching edges which share a common endpoint.</p><p>We could devise an algorithm for this approach, but its processing time is arguably not relevant to users needs (users needs = lightning fast, right here, right now). Probably it would be faster to create a balanced binary search tree with multiple sort keys, almost like a database index file, which maps primary/foreign keys with a set of satisfying records.</p><p>Balanced binary search trees and database indexing will be discussed in a separate article, where we will return to the Airbnb home filtering problem again.</p><p>The Hopcroft-Karp algorithm (and many others) are based on both <strong>DFS</strong> (Depth-First Search) and <strong>BFS </strong>(Breadth-First Search) graph traversal algorithms. To be honest, the actual reason to introduce the Hopcroft-Karp algorithm here is to surreptitiously switch to graph traversals, which is better to start from the nice graphs, binary trees.</p><p>Binary tree traversals are really beautiful, mostly because of their recursive nature. There are three basic traversals called in-order, post-order and pre-order (you may come up with your own traversal algorithm). They are easy to understand if you have ever traversed a linked list. In linked lists you just print the current node’s value (named item in the code below) and continue to the next node.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eeaaacbc62116bf4ab620d3102280302/href">https://medium.com/media/eeaaacbc62116bf4ab620d3102280302/href</a></iframe><p>Almost the same goes with binary trees, you print the node value (or whatever else you need to do with it) and then continue to the next node, but in this case, there are “two next” nodes, left and right. So you should do the same for both left and right nodes. But you have three different choices here:</p><ul><li><strong>print</strong> the node value then go to the <strong>left</strong> node, and then go to the <strong>right</strong> node, or</li><li>go to the <strong>left</strong> node, <strong>print</strong> the node value, and then go to the <strong>right</strong> node, or</li><li>go to the <strong>left</strong> node, then go to the <strong>right</strong> node, and then <strong>print</strong> the value of the node.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f9ce1d7d9e771b78a77beb58a698f37/href">https://medium.com/media/0f9ce1d7d9e771b78a77beb58a698f37/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_REEYbWyGAcxUOg91NpfDQ.png" /><figcaption>Detailed tracing of pre-order traversal</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b8dFEEr0iKEs0ogkCR5mdQ.png" /></figure><p>Obviously, recursive functions look very elegant though they are so expensive. Each time we call a function recursively, it means we call a completely “new” function (see the illustration above). And by “new” we mean that another stack memory space should be “allocated” for the function arguments and local variables. That’s why recursive calls are expensive (the extra stack space allocations and the many function calls) and dangerous (mind the stack overflow) and it is obviously suggested to use iterative implementations. In mission critical systems programming (aircraft, NASA rovers and so on) a recursion is completely prohibited (no stats, no experience, just telling you the rumors).</p><h3>Netflix and Amazon: Inverted Index Example</h3><p>Let’s say we want to store all Netflix movies in a binary search tree with movie titles as sort keys. So whenever a user types something like “Inter”, we will return a list of movies starting with “Inter” (for instance, “Interstellar”, “Interceptor”, “Interrogation of Walter White”).</p><p>Now, it would be great if we’ll return every movie that contains “Inter” in its title (not only ones that start with “Inter”), and the list would be sorted by movie ratings or something that is relevant to that particular user (like thrillers more than drama). The point of this example is to make efficient range queries to a BST.</p><p>But as usual, we won’t dive deeper into the cold water to spot the rest of the iceberg. Basically, we need a fast lookup by search keywords and then get a list of results sorted by some key, which most likely should be a movie rating and/or some internal ranking based on a user’s personalized data. We’ll try to stick to the KISK principle (Keep It Simple, Karl) as much as possible.</p><blockquote>“KISK” or “let’s keep it simple” or “for the sake of simplicity”, a super excuse for tutorial writers to abstract from the real problem and make tons of assumptions by bringing an “abc” easy example and its solution in pseudocode that works even on your grandma’s laptop.</blockquote><p>This problem could be easily applied to Amazon’s product search as we most commonly search something in Amazon by typing a text describing our interest (like “Graph Algorithms”) and get results sorted by product ratings. I haven’t experienced personalized results in Amazon’s search results. But I’m pretty sure Amazon does that stuff too. So, it will be fair to change the title of this subtopic to…</p><p><strong>Netflix and Amazon</strong>. Netflix serves movies, Amazon serves products, we’ll name them “items”, so whenever you read an “item” think of a movie in Netflix or any [viable] product in Amazon.</p><p>What is most commonly done with the items is the parsing of their title and description (<em>we’ll stick to the title only</em>), so if an operator (usually a <em>human being inserting item’s data into Netflix/Amazon database via an admin dashboard</em>) inserts a new item into the database, its title is being processed by some “ItemTitleProcessor” to produce keywords.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sHk85QLf7UBbV3fv0tEpqw.png" /><figcaption>Not the best illustration, I know (and has a typo)</figcaption></figure><p>Each item has its unique ID, which is being linked to the keyword found in its title. This is what search engines do while crawling websites all over the world. They analyze each document’s content, tokenize it (break it into smaller entities called words) and add it to a table, which maps each token (word) to the document ID (website) where the token has been “seen”.</p><p>So whenever you search for “hello”, the search engine fetches all documents mapped to the keyword “hello” (reality is much complex, because the most important thing is the search relevancy, which is why Google Search is so awesome). So a similar table for Netflix/Amazon may look like this (again, think of Movies or Products when reading Items).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fpEI4aYnsQh8weU2sdcOAg.png" /><figcaption>Inverted index</figcaption></figure><p>Hashtables, again. Yes, we will keep a hashtable for this <strong>inverted index</strong> (<em>index structure storing a mapping from content - </em><a href="https://en.wikipedia.org/wiki/Inverted_index"><em>Wikipedia</em></a>). The hashtable will map a keyword to a BST of items. Why BST? Because we want to keep them sorted and at the same time serve them (respond to frontend requests) in sequential sorted portions, (for instance, 100 items at a request using pagination). Not really something that shows the power of BSTs. But let’s pretend that we also need a fast lookup in the search result, say you want all 3 star movies with the keyword “machine”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dInMLLVJp8dFKYJ4iUhGcQ.png" /></figure><p><em>Note that it’s okay to have duplicate items in different trees, because an item usually can be found with more than one keyword</em>.</p><p>We’ll operate with items defined as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79585ae445447ded39385b0c183c6734/href">https://medium.com/media/79585ae445447ded39385b0c183c6734/href</a></iframe><p>Each time a new item is inserted into a database, the title is processed and added to the big index table, which maps a keyword to an item. There could be many items sharing the same keyword, so we keep these items in a BST sorted by their rating.</p><p>When users search for some keyword, they get a list of items sorted by their rating. How can we get a list from a tree in a sorted order? By doing an in-order traversal.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/335ad1fcb684abd18f56935d1a94e8a8/href">https://medium.com/media/335ad1fcb684abd18f56935d1a94e8a8/href</a></iframe><p>Here’s how an implementation of InOrderProduceVector() might look:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31738da745f9cb4b55b9b9b97ade582d/href">https://medium.com/media/31738da745f9cb4b55b9b9b97ade582d/href</a></iframe><p>But, but… We need the highest rated items first, and our in-order traversal produces the lowest rated items first. That’s because of its nature. In-order traversal works “bottom up”, from the lowest to the highest item. To get what we wanted, i.e. the list in descending order instead of ascending, we should take a look at the in-order traversal implementation a bit closer.</p><p>What we are doing is going through the left node, then printing the current node’s value and then going through the right node. The left most node is the node with the smallest value. So simply changing the implementation to go through the right node first will lead us to a descending order of the list. We’ll name it as others do, a reverse in-order traversal.</p><p>Let’s update the code above (introducing in a single listing). Warning - Bugs Ahead!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b524962453cc44796523fffa4db6551/href">https://medium.com/media/5b524962453cc44796523fffa4db6551/href</a></iframe><p>That’s it. We can serve item search results pretty fast. As mentioned above, inverted indexing is used mostly in search engines, like Google. Although Google Search is a <strong>very</strong> complex search engine, it does use some simple ideas (way too modernized though) to match search queries to documents and serve the results as fast as possible.</p><p>We used tree traversals to serve results in sorted order. At this point it might seem that pre/in/post-order traversals are more than enough, but sometimes there is a need for another type of traversal.</p><p>Let’s tackle this well-known programming interview question, “How would you print a [binary] tree level by level?”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N8LEoIDShv0s5jeSdLwccw.png" /></figure><h3>Traversals: DFS and BFS</h3><p>If you are not familiar with this problem, think of some data structure that you could use to store nodes while traversing the tree. If we compare level-by-level traversal of a tree with the others above (pre, in, post order traversals), we’ll eventually devise two main traversals of graphs, that is a depth-first search (DFS) and breadth-first search (BFS).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BINJY5Q9c9x0OPchErAqTg.png" /></figure><p>Depth-first search hunts for the farthest node, breadth-first search explores nearest nodes first.</p><ul><li><strong>Depth-first search</strong> - more actions, less thoughts.</li><li><strong>Breadth-first search</strong> - take a good look around you before going farther.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wEftMOewfDW2ZLjsenZNUg.png" /></figure><p>DFS is much like pre, in, post-order traversals. While BFS is what we need if we want to print a tree’s nodes level-by-level.</p><p>To accomplish this, we would need a queue (data structure) to store the “level” of the graph while printing (visiting) its “parent level”. In the previous illustration nodes that are placed in the queue are in light blue.</p><p>Basically, going level by level, nodes on each level are fetched from the queue, and while visiting each fetched node, we also should insert its children into the queue (for the next level). The following code is simple enough to get the main idea of BFS. It is assumed that the graph is connected, although it can be modified to apply to disconnected graphs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/577240205af8eadc13b6f537c44c9fc6/href">https://medium.com/media/577240205af8eadc13b6f537c44c9fc6/href</a></iframe><p>The basic idea is easy to show on a node-based connected graph representation. Just keep in mind that the implementation of the graph traversal differs from representation to representation.</p><p>BFS and DFS are important tools in tackling graph searching problems (<em>but remember that there are tons of graph search algorithms)</em>. While DFS has elegant recursive implementation, it is reasonable to implement it iteratively. For the iterative implementation of BFS we used a queue, for DFS you will need a stack. One of the most popular problems in graphs and at the same time one of the most possible reasons you read in this article is the problem of finding the shortest path between graph vertices. And this takes us to our last thought experiment.</p><h3>Uber and the Shortest Path Problem (Dijkstra’s Algorithm)</h3><p>With its 50 million users and 7 million drivers (<a href="https://expandedramblings.com/index.php/uber-statistics/">source</a>), one of the most important things that is critical to Uber’s functioning is the ability to match drivers with riders in an efficient way. The problem starts with locations.</p><p>The backend should process millions of user requests, sending each of the requests to one or more (usually more) drivers nearby. While it is easier and sometimes even smarter to send the user request to all nearby drivers, some pre-processing might actually help.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QPrbZuwR78qZgiZySoWv4Q.png" /></figure><p>Besides processing incoming requests and finding the location area based on the user coordinates and then finding drivers with nearest coordinates, we also need to find the right driver for the ride. To avoid geospatial request processing (fetching nearby cars by comparing their current coordinates with user’s coordinates), let’s say we already have a segment of the map with user and several nearby cars.</p><p>Something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6KgEsmbSs6faQPLRLrQ2DA.png" /></figure><p>Possible paths from a car to a user are in yellow. The problem is to calculate the minimum required distance for the car to reach the user, in other words, find the shortest path between them. While this is more about Google Maps rather than Uber, we’ll try to solve it for this particular and very simplified case mostly because there are usually more than one drivers car and Uber might want to calculate the nearest car with the highest rating to send it to the user.</p><p>For this illustration that means calculating for all three cars the shortest path reaching to the user and decide which car would be the optimal to send. To make things really simple, we’ll discuss the case with just one car. Here are some possible routes to reach to the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yv50uskTygpYGN4NbF8CKw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fxRxGd8zX4WphcaW9WlKdg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nyl2FDD3AoBUYD4bP9tijQ.png" /><figcaption>Possible variants to reach the user</figcaption></figure><p>Cutting to the chase, we’ll represent this segment as a graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h8EghvyR-H2rFDClEwF3pA.png" /></figure><p>This is an undirected weighted graph (edge-weighted, to be more specific). To find the shortest path between vertices B (the car) and A (the user), we should find a route between them consisting of edges with possibly minimum weights. You are free to devise your version of the solution. We’ll stick with <a href="https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm">Dijkstra’s version</a>. The following steps of Dijkstra’s algorithm are from <a href="https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm">Wikipedia</a>.</p><p><em>Let the node at which we are starting be called the </em><strong><em>initial node</em></strong><em>. Let the </em><strong><em>distance of node Y</em></strong><em> be the distance from the </em><strong><em>initial node</em></strong><em> to Y. Dijkstra’s algorithm will assign some initial distance values and will try to improve them step by step.</em></p><ol><li><em>Mark all nodes unvisited. Create a set of all the unvisited nodes called the unvisited set.</em></li><li><em>Assign to every node a tentative distance value: set it to zero for our initial node and to infinity for all other nodes. Set the initial node as current.</em></li><li><em>For the current node, consider all of its unvisited neighbors and calculate their tentative distances through the current node. Compare the newly calculated tentative distance to the current assigned value and assign the smaller one. For example, if the current node A is marked with a distance of 6, and the edge connecting it with a neighbor B has length 2, then the distance to B through A will be 6 + 2 = 8. If B was previously marked with a distance greater than 8 then change it to 8. Otherwise, keep the current value.</em></li><li><em>When we are done considering all of the neighbors of the current node, mark the current node as visited and remove it from the unvisited set. A visited node will never be checked again.</em></li><li><em>If the destination node has been marked visited (when planning a route between two specific nodes) or if the smallest tentative distance among the nodes in the unvisited set is infinity (when planning a complete traversal; occurs when there is no connection between the initial node and remaining unvisited nodes), then stop. The algorithm has finished.</em></li><li><em>Otherwise, select the unvisited node that is marked with the smallest tentative distance, set it as the new “current node”, and go back to step 3.</em></li></ol><p>Applying this to our example, we’ll start with vertex B (the car) as the initial node. For first two steps:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TJlybxA2sd73xKk_G3zFdg.png" /></figure><p>Our unvisited set consists of all vertices. Also note the table at the left side of the illustration. For all vertices, it will contain all the shortest distances from B and the previous (marked “Prev”) vertex that lead to the vertex. For instance the distance is 20 from B to F, and the previous vertex is B.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nnTYJcutyrQ3owuWfcFsKQ.png" /></figure><p>We are marking B as visited and move it to its neighbor F.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-q06mg5A5Yirmu2qHZgL0Q.png" /></figure><p>Now we are marking F as visited and choosing the next unvisited node with smallest tentative distance, which is G. Also note the table at the left side. In the previous illustration nodes C, F and G already have their tentative distances set with the previous nodes which lead to the mentioned nodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8y39ufJ1FEYqjpBJQ9ApcA.png" /></figure><p>As stated in the algorithm, if the destination node has been marked visited (when planning a route between two specific nodes as in our case) then we can stop. So our next step stops the algorithm with the following values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mxxxszr1m82FEtkgcHGHgg.png" /></figure><p>So we have both the shortest distance from B to A and the route through F and G nodes.</p><p>This is really the simplest possible example of potential problems at Uber, comparing this to our iceberg analogy, we are at the <strong>tip</strong> <strong>of the tip</strong> of the iceberg. However, this is a good first start to explore the real world of graph theory and its applications. I didn’t complete what I initially planned for in this article, but in the near future, most probably, this will be continued (also including database indexing internals).</p><p>There is still so much to tell about graphs (still need to study). Take this article as another tip of the iceberg. If you have read this far, you definitely deserve a cookie. Don’t forget to clap and share. Thank you.</p><h4>Resources</h4><p>[1] <a href="https://www.amazon.com/Graph-Algorithms-Shimon-Even-ebook/dp/B00INYG6O4/">Sh. Even, G. Even, Graph Algorithms</a></p><h4>Further reading</h4><p><a href="https://www.amazon.com/Algorithms-4th-Robert-Sedgewick/dp/032157351X/">R. Sedgewick, K. Wayne, Algorithms</a></p><p><a href="https://www.amazon.com/Introduction-Algorithms-3rd-MIT-Press/dp/0262033844/">T. Cormen, Ch. Leiserson, R. Rivest, C. Stein, Introduction to Algorithms</a></p><p><a href="https://www.amazon.com/Expert-proficient-programmer-learning-practices/dp/1838552650/">Expert C++ (why not)</a></p><p>Airbnb Engineering, <a href="https://medium.com/u/ebe93072cafd">AirbnbEng</a></p><p>Netflix Tech Blog, <a href="https://medium.com/u/c3aeaf49d8a4">Netflix Technology Blog</a></p><p><a href="https://blog.twitter.com/engineering/en_us.html">Twitter Engineering Blog</a></p><p><a href="https://eng.uber.com/">Uber Engineering Blog</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c96572a1401" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/i-dont-understand-graph-theory-1c96572a1401">How to think in graphs: An illustrative introduction to Graph Theory and its applications</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Self-Organizing Sorted Linked List in C++]]></title>
            <link>https://medium.com/@vardanator/self-organizing-sorted-linked-list-in-c-ae24b7e0b600?source=rss-d2445cca3a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae24b7e0b600</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[linked-lists]]></category>
            <category><![CDATA[cpp]]></category>
            <dc:creator><![CDATA[Vardan Grigoryan (vardanator)]]></dc:creator>
            <pubDate>Fri, 09 Feb 2018 18:16:27 GMT</pubDate>
            <atom:updated>2020-04-17T23:29:32.150Z</atom:updated>
            <content:encoded><![CDATA[<h4>How would Frankenstein implement a doubly linked list?</h4><p>We are going to create a monster, a doubly linked list, working as a self-organizing list and having additional pointers to interpret its data in a sorted order. All with fancy illustrations, so you would never need another tutorial on how does a linked list work. If you are new to linked lists, this is gonna take some effort to dive in. Prepare for the worst. It’s worth it. No doubt.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8O_qLhwVULXBY3ZzyxATnA.png" /></figure><p>If you are familiar with pointers and know <a href="https://www.amazon.com/Expert-proficient-programmer-learning-practices/dp/1838552650/">how they work</a>, skip to part “Hodog”, otherwise start with “No hodog”. (Also, I personally recommend to <a href="https://www.amazon.com/Expert-proficient-programmer-learning-practices/dp/1838552650/">read this book</a>)</p><h3>No hodog</h3><p>With great power comes great bills for electricity. With great abstraction comes great misunderstanding. Programmers nowadays suffer from these “abstractions” and “misunderstandings”. There are tons of layers of abstractions in programming, which make it sort of “redundant” to understand the internals or to look under the hood of programs, which we will try to do now. Just a little bit, with the help of abstractions. So, there are two main components interesting at this point, it’s the CPU (Central Processing Unit) and the RAM (Random Access Memory).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*erhDpNnLzL-Ch0D_6Kjn-Q.png" /><figcaption>CPU interacts with RAM via buses</figcaption></figure><p>We will concentrate on the yellow thing, the RAM. Whenever we declare a variable, it will take some specified place in the RAM (well, an easy abstraction). We’ll assume that each box on the illustration above represents 1 byte memory, so if we declare a variable that takes 4 bytes, it means 4 boxes should be occupied by it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n1QoDfbhxYsbCwlklJlHIg.png" /><figcaption>Variable declaration and the memory</figcaption></figure><p><em>You might see illustrations like the previous one in other tutorials, but with opposite address ordering, starting from the bottom. In this context there is no any difference between illustration approaches.</em></p><p>We assume that <strong>int</strong> takes <strong>4 bytes</strong> and <strong>char</strong> takes <strong>1 byte</strong>, so again, to get more illustrative:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EEXz6nl75nAXnjzWzp-LcA.png" /><figcaption>The same, with more painting</figcaption></figure><p>We wrote hexadecimal (same decimal, with extra <strong>hexa</strong>s) numbers near each box, because we wanted to emphasize that each box has its unique address. Memory consists of boxes, each of which has its unique address. Each box is able to hold 1 byte data. That’s all we need to know to move on to...</p><p><strong>Pointers</strong>. Now that we see that a variable has its type (which is needed to calculate how many boxes will be needed to store the data) and an address, we could come up with a question. What about the name? No, not that question. Can we store the address of a variable? Yes, we can.</p><blockquote><em>Side note</em>: To really go deeper into pointers, memory structure, and all the fundamental stuff from C++ perspective, <a href="https://www.amazon.com/Expert-proficient-programmer-learning-practices/dp/1838552650/">refer to this book</a>.</blockquote><p>There are specialized data types called pointers, allowing to store a variable’s address and access to that variable via that address. You already knew that. But seriously, what about the name? Mm, turns out it’s just a convenient way for programmers to operate with data, CPU operates with memory boxes by their <strong>relative</strong> addresses. Relative to the beginning. It takes constant time to access any box if you know how far is it from the first box. “How far from the first box” is called offset. That’s how arrays work. Contiguous data blocks of the same type.</p><pre>int arr[4] = {44, 55, 66, 88};</pre><p>Here’s how arr could be illustrated:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Aap7fnEMx1nVjbVeu44dg.png" /></figure><p>Making this illustration more compact (we use different colors throughout this tutorial to give each color a chance to express itself), let’s assume each box contains 4 bytes of data, but before that, a small remark on so-called “endianness”, it’s about the byte ordering in memory boxes. No worries on byte ordering if you declare a ‘char’ variable, as it takes just 1 byte (one box), things get confusing when we have a variable taking more than a byte. We can place those bytes in two opposite orders, first byte starting first or last byte starting first. The following illustration from Wikipedia is more than enough to understand the difference between little-endian and big-endian byte ordering:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*aGNv4xBifMCOhx5U16IpYg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*X62Yc4R6Jxr8qYJC6rk9tg.png" /><figcaption>From Wikipedia</figcaption></figure><p>There are systems supporting little-endian byte ordering, and systems supporting big-endian ordering. What’s the point of having two different approaches? Well, it’s easy to answer, [in programming] whenever there are two or more choices, there will be two or more standards. This is called “Standardizato ad Quantum Absurdum”. I made it up, there is no such thing, but you can call anything that could be done in one way, but instead is done in all possible “different” ways simultaneously, a “Standardizato ad Quantum Absurdum”.</p><p>Back to our array declaration, let’s make a simpler illustration, let’s assume that each memory box represents 4 bytes. So int arr[4] = {44, 55, 66, 88} could be illustrated like this (my painting will be better soon, I promise):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0CvByplDwQsVXDb-yHa_tw.png" /><figcaption>4 byte memory boxes</figcaption></figure><p>Pay attention to addresses, arr[0] resides at addresses 0x5000 through 0x5003 bytes (4 consecutive bytes), arr[1] at 0x5004 through 0x5007 and so on. The illustration above is done just to illuminate one deceptively simple idea of contiguous memory locations. Any array element could be accessed in constant time, and by constant time we mean that element access is done in <strong>k operations </strong>(starting address + number of bytes to jump to target element’s address), and each such element access would take up to k operations each time. Just because array elements are of the same type, all we need to know is its first element’s address, e.g. where does the array start at all. Having the starting address and having the type of an element, we know how many bytes should be read to fetch one element. To access some j-th element, we may just “jump” to that particular location by adding j to the starting address of the array (with respect to element type size, shown a couple of illustrations ago). This could be a crucial point, because sooner we will discuss linked lists, where unfortunately such luxury isn’t an option. And this is one of the most asked interview question: “What is the difference between a vector and a linked list?”.</p><p>We got the picture, now get back to pointers. What happens when we declare a pointer.</p><pre>int* ptr;</pre><p>Same thing that would happen to a declared variable, int var;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tSZEEwFaRctmQsdICKBy2g.png" /><figcaption>Pointer is just another variable</figcaption></figure><p>Turns out pointer is just a disguised variable. Its only difference is the declaration style, using * (asterisk) after the type name, which means that this variable is kind of “special”, it is able to store addresses, actual addresses of actual variables. You are able to get the address of any variable in <a href="https://www.amazon.com/Mastering-Programming-programmer-learning-practices/dp/1838552650/">C++</a> using a special operator for that, &amp; (ampersand). Put it in front of any variable, and it will return the address at which variable resides.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h7opnzfgUu6pPLU94X6VZA.png" /><figcaption>Assigning an address to a pointer.</figcaption></figure><p>So what’s the point of having the address of a variable stored in another variable. Well, the actual usefulness of pointers comes in really handy when operating with dynamic memory (we’ll discuss later in Hodog section), now, we could use this pointer to access that variable without mentioning its name. For instance, if you want to assign that variable a new value, say 15, you just write *ptr = 15; . Or just print its value, cout &lt;&lt; *ptr; .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FMNwVz2LhCZbICgO402SSQ.png" /><figcaption>Accessing a variable via some pointer</figcaption></figure><p>Take a good look at the illustration above. It discusses 3 cases,</p><ol><li>Printing ptr , which does simply print ptr’s value, in this example, 0x5000 .</li><li>Printing &amp;ptr, which prints ptr’s address, e.g. at which address does ptr reside in memory.</li><li>Printing *ptr , which takes ptr’s value, which is just an address, finds a memory box which resides at that very address and returns that box’s content. This case is harder to understand if you are totally new to pointers, so, take a look at the following illustration:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LrYvS_yh4_IQ7nVhK6fGrg.png" /><figcaption>Dereferencing a pointer</figcaption></figure><p>Easy peasy. Pointers are really easy to understand if you imagine them in memory boxes. It’s easier than drawing a Patrick in two easy steps. Finally, the following illustration shows a more abstract way to illustrate pointers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oLQVeQ5CHVelZiniDE_EGA.png" /><figcaption>More abstract way to illustrate pointers</figcaption></figure><p>We will mostly use the last approach, if you will have doubts, you can always refer to the following “associative” illustration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BCEAL4vkfK3rbxP9292jag.png" /><figcaption>Two approaches to our illustrations</figcaption></figure><p>Pay attention to the last lines:</p><pre>int* pa = &amp;arr[0];<br>int* pxa = pa + 1;</pre><p>We’ve added them on purpose, to torture your brain (in case you are new to pointers).</p><h3>Hodog</h3><p>Linked lists are data structures. That’s it. Go read more on <a href="https://en.wikipedia.org/wiki/Linked_list">Wikipedia</a> or <a href="https://www.amazon.com/Mastering-Programming-programmer-learning-practices/dp/1838552650/">somewhere helpful to me</a>. A linked list is usually described by its Node structure and standard operations on nodes (insert, remove, fetch/find):</p><pre>struct ListNode<br>{<br>  Type item;<br>  ListNode* link; // next<br>};</pre><p>ListNode describes (defines) a single list element. In case of arrays, we would use only the “item”. Linked list nodes usually require more data to be able to show us its neighbor node. For the sake of simplicity, let’s just define two types of data structures: 1) contiguous, 2) node-based, the latter being of our interest. Node-based data structure’s nodes are spread across memory, which means that we can use a node’s link to refer it to another node, eventually creating a whole network of hand shaking nodes. Arrays, in the contrary, are contiguous, ensuring their elements reside close to each other:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nO1hzqSGLXzVuKzFkvK4rA.png" /><figcaption>Illustrations are better than words</figcaption></figure><p>So, being more specific, let’s compare an array of integers with a linked list containing integer items. To define each list node, we will use a structure like this:</p><pre>struct ListNode<br>{<br>  int item;<br>  ListNode* next;<br>};</pre><p>The following code shows an array declaration and further element insertion, and then a linked list declaration and node insertions:</p><pre>int arr[3]; // array of integers, containing three elements<br>arr[0] = 21;<br>arr[1] = 32;<br>arr[2] = 34;</pre><pre>ListNode* head = new ListNode(); // yep, magic happens with &#39;new&#39;<br>head-&gt;item = 21;<br>head-&gt;next = new ListNode();<br>head-&gt;next-&gt;item = 32;<br>head-&gt;next-&gt;next = new ListNode();<br>head-&gt;next-&gt;next-&gt;item = 34; // a bit of confusing, isn&#39;t it?</pre><p>If you are not familiar with thenew operator, go read on the web, we can’t spend much time on it in this article. Let’s just remind that there usually is a separation of memory into two types, stack and heap. Heap is also called dynamic memory, meaning it will be dynamically allocated whenever requested (by new operator). You might have seen already illustrations like below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SVFdVFjKB1p81ntHH7SGuA.png" /></figure><p>The illustration above is not much “valid”. In reality, both stack and heap are parts of the “same” virtual memory. Just imagine the same old memory separated into two parts, one of them being called <strong>stack memory</strong>, and the other one <strong>dynamic memory</strong>. So we will use a hardcore illustration (see below), also pay attention to the sequence of expressions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wR-ZybVRcjF8FA6HGarf7Q.png" /></figure><p>So using this illustration, we can depict previous code (array and list creation/initialization). The following illustration contains step by step code mapping, take your time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XF5TJA-UOgk-hF6251aSDg.png" /></figure><p><em>There are plenty of more professional illustrations on the web </em><a href="https://medium.com/fhinkel/confused-about-stack-and-heap-2cf3e6adb771"><em>from proven professionals</em></a><em>, depicting a better “real-life” situation. The main point of having [at least] two different memory areas for programs is to ease the execution of different blocks of code and managing variables’ lifetimes. See, stack is a “kind of” fixed-sized memory, it can’t be used to create a constantly increasing container elements. Whenever you declare a variable, you command the compiler to allocate a space for that strongly-typed variable, e.g. an integer, taking 4 bytes, or a double, taking 8 bytes and so on, but whenever you need something that “grows” continuously, i.e. you are not able to predict its size while declaring a name for it (say, keeping records of watched movies), but want to make sure it will have enough space (and not more than needed) to hold elements when the time comes (when you watch a new movie and add to the list of already watched movies), you can’t operate on the stack, as stack is a provision of memory for variables whose size is already known. Heap helps with this kind of problems. It provides you a bucket of available memory. Take a byte whenever you need one.</em></p><p>As linked list grows as it goes, it’s a real good candidate to use for storing elements or more precisely, a collection of elements. Imagine we declared a linked list to store movie titles of already watched movies (by Patrick). Patrick already watched “Interstellar”, so we could do something like this:</p><pre>LinkedList movies;<br>movies.Insert(&quot;Interstellar&quot;);</pre><p>While program runs (suppose it runs days and weeks) and Patrick keeps watching new movies, the list grows.</p><pre>movies.Insert(&quot;Sponge Bob episode 10&quot;);<br>movies.Insert(&quot;Sponge Bob episode 4&quot;); </pre><p>What we gonna do now is implement list insertion and deletion functions to show the main differences from arrays. Before the actual implementation, let’s discuss the types of list nodes. As mentioned above, a list node could be represented as a structure having two fields, one for the actual element’s value (the payload), and the other for linking to the next node. We will add another pointer to this structure, to make it able to keep records for both left and right neighbors.</p><pre>struct ListNode<br>{<br>  std::string item;<br>  ListNode* next;<br>  ListNode* prev;<br>};</pre><p>Here’s how we most likely would illustrate such list node:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GqnK7_URdj0d0uUDlC5YJQ.png" /><figcaption>Simple illustration of doubly linked list node</figcaption></figure><p>The main issue with a list node is the additional pointer variables. Comparing with arrays, if we are storing 10 integers each taking 4 byte memory, an array would require just 10*4 bytes of memory to store the actual elements and an additional pointer to that memory’s starting address, which again, would take 4 or 8 bytes. So for storing 10 integers, we will need 44 bytes (or 48 bytes, depending on the pointer size). Before showing similar calculations for a doubly linked list, let’s assume a pointer will take 4 bytes of memory, i.e. we are operating in 32-bit system. Pointer takes 4 bytes of memory on 32-bit systems as it’s a variable, which allows to store address values, and an address value in 32-bit system has 32-bit length, i.e. 4 bytes. In case of working in a 64-bit system, a pointer would take 8 bytes of memory, as it would hold an address value, which length would be 64 bit, i.e. 8 bytes. For simplicity, we will assume pointers are 4 bytes. So, an array of 10 integers requires 44 bytes of memory. To store one integer in a doubly linked list node, we need 4 bytes for the ‘item’, and additional 8 bytes for ‘next’ (4 byte pointer) and ‘prev’ (4 byte pointer) pointers, which sums up to 12 bytes for just one node. And to store 10 such integers we will need 12*10 bytes = 120 bytes of memory (we’re ignoring additional ‘head’ or ‘tail’ pointers for now, also ignoring <a href="https://en.wikipedia.org/wiki/Data_structure_alignment">memory alignment</a> issues).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ARJlR2UHmQRkKu66ORwzUA.png" /><figcaption>A little details</figcaption></figure><p>Let’s make it even harder to imagine. Whenever we are storing two strings in a list like this:</p><pre>struct ListNode<br>{<br>  std::string item;<br>  ListNode* next;<br>  ListNode* prev;<br>  ListNode() : next(nullptr), prev(nullptr) {} // meh<br>};</pre><pre>// .. other code</pre><pre>ListNode* node = new ListNode();<br>node-&gt;item = &quot;Interstellar&quot;;<br>node-&gt;next = new ListNode();<br>node-&gt;next-&gt;item = &quot;Sponge Bob&quot;;</pre><p>We will picture that list as the left side of the following illustration, however, it will look really different in memory (the right side of the illustration). It is again, simplified, the real memory layout looks slightly different, but the illustration helps one to picture what’s going under the hood while declaring or creating linked list nodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T8zxXkSX6G793wlJ9zkkFQ.png" /><figcaption>More details, yet again, simplified</figcaption></figure><p>In a more professional approach, creating and operating with bare list nodes like we did above is not much accepted. Instead, a LinkedList class is suggested, which will hide all the implementation details (that’s why sometimes lists and other data structures are called ‘abstract data types’). We will show the bare minimum of a LinkedList class and will implement element insertion (with fancy illustrations) before we finally will reach Frankenstein’s list. So here’s what we are going to code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Gm2cJmok8q7NFUNS4CtTg.png" /></figure><p>See the additional pointers? Head and tail. We will use the tail pointer to insert or access list elements from the end, it also allows constant time insertion at the end. Head pointer is the main access point of the entire list.</p><pre>template &lt;typename T&gt;<br>class LinkedList<br>{<br>protected:<br>  struct Node<br>  {<br>    T item;<br>    Node* next;<br>    Node* prev;<br>    Node() : next(nullptr), prev(nullptr) {}<br>    Node(const T&amp; i) : item(i), next(nullptr), prev(nullptr) {}<br>  };</pre><pre>public:  <br>  const T GetItemAt(int pos) const;</pre><pre>  void InsertAt(const T&amp; elem, int pos);<br>  void PushFront(const T&amp; elem);<br>  void PushBack(const T&amp; elem);</pre><pre>  void RemoveAt(int pos);</pre><pre>  void Traverse(void (*visit)(const T&amp;)) const;</pre><pre>private:<br>  Node* head_;<br>  Node* tail_;<br>  int size_;<br>};</pre><p>We have three functions for element insertion, to insert at the front, at the end and at any other position in the list. These three functions are emphasized just because we have to discuss three different cases of list element insertion. It’s because for each case we should take care for nodes’ next and prev pointers. Here’s an illustration of insertion at the front of the list:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qC46VYfHqqUKojUOJETK8Q.png" /></figure><p>As you can see, the most important thing while inserting at the front of the list is to properly update the ‘head’ pointer. Here’s a sample implementation:</p><pre>void PushFront(const T&amp; elem)<br>{<br>  Node* node = new Node(elem);<br>  if (head_) {<br>    head_-&gt;prev = node;<br>  } else {<br>    tail_ = node;<br>  }<br>  node-&gt;next = head_;<br>  head_ = node;<br>  ++size_;<br>}</pre><p>Almost the same goes with the element insertion at the end:</p><pre>void PushBack(const T&amp; elem)<br>{<br>  Node* node = new Node(elem);<br>  if (!head_) {<br>    head_ = node;<br>    tail_ = node;<br>  } else {<br>    tail_-&gt;next = node;<br>    node-&gt;prev = tail_;<br>    tail_ = node;<br>  }<br>  ++size_;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ev9du9NJL5kiLA-lHvcmUQ.png" /></figure><p>Final and even more interesting case is the insertion at any [valid] position of the list. Inserting at any position also involves inserting at the front or at back of the list, so we should check the corresponding cases to handle them properly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LZtCxhpZaAmMqIWeOrMVAw.png" /></figure><p>Here’s a possible implementation:</p><pre>void Insert(const T&amp; elem, std::size_t pos)<br>{<br>  if (<strong>pos == 0</strong>) {<br>    return PushFront(elem);<br>  }<br>  if (<strong>pos &gt;= size_</strong>) { // insert at the end even if pos is way bigger<br>    return PushBack(elem);<br>  }<br>  Node* node = new Node(elem);<br>  Node* cur = <strong>GetNodeAt_(pos)</strong>;<br>  node-&gt;next = cur;<br>  node-&gt;prev = cur-&gt;prev;<br>  cur-&gt;prev-&gt;next = node;<br>  cur-&gt;prev = node;<br>  ++size_;<br>}</pre><p>We used a GetNodeAt_ private function (private as it returns a Node* by its position), here’s its implementation:</p><pre>Node* GetNodeAt_(std::size_t pos) const<br>{<br>  // be careful, there might be a bug<br>  std::size_t count = 0;<br>  Node* cur = nullptr;<br>  if (pos &gt; size_ / 2) {<br>    cur = tail_;<br>    while (count != (size_ - pos)) {<br>      cur = cur-&gt;prev;<br>      ++count;<br>    }<br>  } else {<br>    cur = head_;<br>    while (count != pos) {<br>      cur = cur-&gt;next;<br>      ++count;<br>    }<br>  }<br>  return cur;<br>}</pre><p>As we store both head and tail pointers, we can halve the number of node checks based on the value of the position. If it’s bigger than the half of the list elements, than we could reach to it from tail, otherwise from head.</p><p><strong>What about node removal?</strong> Almost the same as insertion, deletion of a node has three special cases, from the front, from the end and deletion of a node at any position. We won’t bring detailed illustrations or even a source code samples for deletion and the rest of the operations for simple doubly linked list. Try to come up with own implementation for a simple doubly linked list, while we will meet the Frankenstein’s monster!</p><h3>Self-organizing list vs sorted list</h3><p>Linked list operations allow some better performance comparing to arrays. For example the PushFront() function inserts a new item into list in constant time, meaning it does the same amount of work each time, despite the number of already existing elements in the list, e.g. has no dependency on N (magic letter used to identify the variable amount of data count in data structures and algorithms). To insert a new element at the front of an array, we have to move N already existing array elements to make a space for that new element. This makes new element insertion a very expensive operation for an array (we’re talking about the front insertion). But this doesn’t mean that lists are fast. That’s why programmers are trying to improve simple lists to achieve more horsepower. One of such improvements is self-organizing list. The idea is very simple, whenever client code accesses an element, that element advances its position (moves closer to the front), which makes it to be accessed faster the next time, and even faster after that.</p><p>And sorted list is a list which keeps its elements in a sorted order. By combining these two ideas, we are going to make a monster linked list, as promised in the beginning of this tutorial.</p><p>First, let’s look at the node of self-organizing sorted linked list (we gonna call it a <strong>Frankenstein’s list</strong> from now on):</p><pre>struct Node<br>{<br>  T item;<br>  Node* next;<br>  Node* prev;<br>  Node* <strong>greater</strong>;<br>  Node* <strong>lesser</strong>;<br>};</pre><p>Two new pointers appeared, greater and lesser. These new pointers allow to traverse the list in a sorted order, both ascending and descending, that’s why there are two pointers ( greater for ascending order and lesser for descending). Here’s a illustration of a monstrous node:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BHk9pcbI5e5NwOzYfC9uhA.png" /><figcaption>Frankenstein list node</figcaption></figure><p>Having two more pointers for ascending and descending order of nodes also means we should have two more pointers as ‘head’ and ‘tail’ pointers for our entire list, i.e. a head pointer that points to the smallest node and a tail pointer that points to the biggest node. And these nodes have nothing to do with our ‘head’ and ‘tail’ pointers for accessing list nodes as usual (as we did it previously for doubly linked list). So, a class definition for Frankenstein’s list may look like the following:</p><pre>template &lt;typename T&gt;<br>class FrankensteinList<br>{<br>protected:<br>  struct Node<br>  {<br>    T item;<br>    Node* next;<br>    Node* prev;<br>    Node* greater;<br>    Node* lesser;<br>    // assume a constructor initializing pointers to nullptr<br>  };</pre><pre>public:<br>  void Insert(const T&amp; elem);<br>  // other methods<br>  // ...</pre><pre>private:<br>  Node* head_; // same as for simple doubly linked list<br>  Node* tail_; // same as before<br>  <strong>Node* asc_head_;</strong> // access nodes in ascending order<br>  <strong>Node* desc_head_;</strong> // access nodes in descending order<br>  std::size_t size_;<br>};</pre><p>Two new pointers, asc_head_ and desc_head_ , each of which points to corresponding node in proper order. Let’s picture a Frankenstein list consisting of integers <strong>5, -3, 1, 22, 0, 8</strong>. While the head pointer points to the first node, i.e. 5, and the tail pointer points to the last node, 8, ascending head pointer must point to a node having minimum value among others. And in a similar manner, descending head pointer points to node with maximum value. Here’s an illustration, keep in mind, nodes have been “back inserted” in this order 5, -3, 1, 22, 0, 8.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IE3Ik0OC2COeZ0iqtvWpyw.png" /><figcaption>Frankenstein’s list</figcaption></figure><p>This is the one of few cases where illustration is harder to understand than the actual code. Patrick’s first reaction after seeing this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k1QyR6acWIX_l5Cfnq18XA.png" /><figcaption>List, Patrick, Frankenstein’s list</figcaption></figure><p>Anyway, if we try to examine the list we’ll see that the whole chaos in the illustration is because of lesser and greater pointers. Try to find the asc_head pointer, it points to the minimum node in the list. If we try to go through greater pointer (in blue) of that node, we will reach to the next minimum node, which is greater than previous one, but is lesser than all other nodes in the list. So, greater pointer allows us to traverse through list nodes in ascending order. In the contrary, to traverse the list nodes in descending order, we will start from desc_head pointer and continue through lesser pointers. In the illustration above, desc_head points to 22, the biggest node in the list, and 22’s lesser pointer points to 8, the next biggest node, which is less than 22 but is greater than all other nodes in the list. For Patrick’s sake, let’s depict a much simpler example with 3 nodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RAYk9WhYdJpYAli4qix1DA.png" /><figcaption>Frankenstein’s list with three nodes</figcaption></figure><p>This is much better. So what’s the purpose of having such a monster? Well, first of all we should admit that the memory overhead is too much, because we store 4 pointers with a single data item, e.g. if we store an integer (4 bytes) in a Frankenstein’s list node it will take additional 16 bytes of memory just to save its next/prev and greater/smaller pointers, and overall a 20 byte of memory for one integer node. In a simplest case it’ll take ~2Kb to save 100 integers. In the contrary, an array will take ~0.4Kb. However, in real life we operate with big enough objects and sometimes <strong>not</strong> caring for small memory overheads over efficient data lookups is considered a good practice. Say, we have to save a full movie data, its title, release date, directors’ names, actors names, movie posters, quotes from the movie, URLs to it’s home page/trailer video/discussion threads/etc. And let’s assume that a single movie object will require ~1Mb of memory, so to save 100 movie objects in an array, we’d need exactly 100Mb memory + 4 byte pointer to array. To save 100 movie objects in Frankenstein’s list, we’d need 100Mb + 1.6Kb (we again assume that we operate in a 32-bit system). Overhead is arguably acceptable for big enough objects. The good part with Frankenstein’s list is that we always have its elements in sorted order, both ascending and descending. Imagine you put a large such list in a data grid, or some table, and viewing the items in a sorted order will run really smoothly.</p><p>The next big thing with Frankenstein’s list is its self-organizing nature. As mentioned earlier, the idea behind a self-organizing list is simple, whenever a node is being accessed, we advance its position to the front. This makes accessing the same element faster the next time. Let’s illustrate this idea for a simple list (for the sake of brevity we’ll omit greater/lesser pointers in the illustration below):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mLkgDn9TSfsNfpnTYZeuZA.png" /><figcaption>Self-organizing list</figcaption></figure><p>The illustration above shows how a node advances its position when it is being accessed. By advancing its position it makes faster to access the same element the next time. You can call it an “in-place caching”.</p><p>As always, there are many ways to implement a self-organizing list, one of them is keeping an access counter, e.g. recording how many times a particular element had been accessed and moving it to appropriate position. Another way to implement it is moving an accessed element right to the front, making it the first element in the list. The approach illustrated above makes a single swap with accessed node’s left node (the one closer to the front). So a Frankenstein’s list is a list with which self-organizes itself and keeps nodes’ sorted order. Here comes the code.</p><p>You can find the full <a href="https://github.com/vardanator/ultron/blob/master/src/lists/self-organizing-sorted-list.h">source code here</a> (a bunch of good tests needed though).</p><p>Let’s just discuss the interesting parts, node insertion. Again, insertion has three cases, at the front, at the back and at any other position.</p><pre>void InsertAt(const T&amp; item, const std::size_t pos)<br>{<br>  if (pos == 0) {<br>    return PushFront(item);<br>  }<br>  if (pos &gt;= size_) { // you&#39;ve seen this before<br>    return PushBack(item);<br>  }<br>  Node* node = new Node(item);<br>  std::size_t count = 0;<br>  Node* cur = head_;<br>  while (count != pos) {<br>    ++count;<br>    cur = cur-&gt;next;<br>  }<br>  cur-&gt;prev-&gt;next = node;<br>  node-&gt;prev = cur-&gt;prev;<br>  cur-&gt;prev = node;<br>  node-&gt;next = cur;<br>  ++size_;</pre><pre><strong>  PutInSortedOrder_(node);</strong><br>}</pre><p>The most interesting part of the code above is the last line: PutInSortedOrder_(node). This private function makes sure to update the list’s sorted order by placing this new node in the right position:</p><pre>void PutInSortedOrder_(Node* node)<br>{<br>  if (!node) return;<br>  if (!asc_head_) {<br>    asc_head_ = node;<br>    desc_head_ = node;<br>    return;<br>  }</pre><pre>  Node* cur = asc_head_;<br>  while (cur-&gt;item &lt; node-&gt;item &amp;&amp; cur-&gt;greater) {<br>    cur = cur-&gt;greater;<br>  }<br>  if (cur-&gt;item &lt; node-&gt;item) {<br>    node-&gt;greater = cur-&gt;greater;<br>    cur-&gt;greater = node;<br>    node-&gt;lesser = cur;<br>    if (!node-&gt;greater) {<br>      desc_head_ = node;<br>    }<br>  } else {<br>    node-&gt;lesser = cur-&gt;lesser;<br>    if (cur-&gt;lesser) {<br>      cur-&gt;lesser-&gt;greater = node;<br>    } else {<br>      asc_head_ = node;<br>    }<br>    node-&gt;greater = cur;<br>    cur-&gt;lesser = node;<br>  }<br>}</pre><p>The code above is not an elegant implementation, but it shows how do we deal with new node insertion. At first we should just insert the new node as before, by properly updating its and its neighbors’ prev and next pointers. After that, we should take care of the list’s overall sorted order, by updating new node’s and its “sorted” neighbors’ greater and lesser pointers, respectively. Node removal is similar to node removal of a doubly linked list, with a little quirk of taking care of the sorted order. Find a sample implementation <a href="https://github.com/vardanator/ultron/blob/master/src/lists/self-organizing-sorted-list.h">here</a>.</p><p>Finally, we should worry about Frankenstein’s list self-organizing nature.</p><pre>const T GetAt(const std::size_t pos)<br>{<br>  if (pos &gt;= size_) {<br>    throw std::out_of_range(&quot;Invalid position&quot;);<br>  }<br>  Node* cur = head_;<br>  std::size_t count = 0;<br>  while (count &lt; pos) {<br>    cur = cur-&gt;next;<br>    ++count;<br>  }<br>  <strong>AdvanceNode_(cur);</strong><br>  return cur-&gt;item;<br>}</pre><p>Pay attention to the AdvanceNode_() function. It has been called just before returning the required item at corresponding position. AdvanceNode_() is a private function whose only purpose is to swap itself with the left neighbor. For the sake of brevity we won’t bring its implementation here, instead you can find it and other methods’ implementations at the <a href="https://github.com/vardanator/ultron/blob/master/src/lists/self-organizing-sorted-list.h">same place</a>.</p><p><em>Please leave a comment if you find any issue with the code or illustrations.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae24b7e0b600" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Google Sticker on your GitHub profile: mastering GitHub contributions art]]></title>
            <link>https://medium.com/@vardanator/google-sticker-for-your-github-profile-mastering-github-contributions-art-f4c833c12bcf?source=rss-d2445cca3a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4c833c12bcf</guid>
            <category><![CDATA[creativity]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[geek-culture]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[bash]]></category>
            <dc:creator><![CDATA[Vardan Grigoryan (vardanator)]]></dc:creator>
            <pubDate>Mon, 15 Jan 2018 21:08:16 GMT</pubDate>
            <atom:updated>2018-01-17T18:49:30.477Z</atom:updated>
            <content:encoded><![CDATA[<p>Just for fun. Short reading. <strong>#GitHubArtChallenge</strong></p><p>If you had a full year of empty contributions to your GitHub repositories, that’s a real chance to look lazy (most of us do work at BitBucket, as it provides free private repositories for up to 5 collaborators). GitHub profile is something that shows your “passion to contribute to open source”. You will code for free only if you love to code. At least some top companies would think so while hiring the best possible programmers. They look for the passion. Speaking of top tech companies, Google comes in mind.</p><p>So, I’ve decided to fill my gaps of contributions by making a Google sticker on my GitHub profile.</p><p>Before Google sticker:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3VOYyMSLIH_J_OvjGUEkxQ.png" /><figcaption>This is how average contributions history/graph looks like</figcaption></figure><p>After Google sticker:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sgy0jIjpPvnRokJl7E60Tw.png" /><figcaption>This is how your GitHub sticker will look like</figcaption></figure><p>Looks creative, doesn’t it? I chose Google just for fun, it’s much shorter than Amazon or Facebook aaaand it’s much more recognizable than AwsmTechAiBasedBlockchainCompanyWhereImTheCEOBitch LLC.</p><p>Here’s the bash script I coded (not the best possible solution, I know) to push commits with backdate. And I pushed random junk source files (and many such files) to increase my CodeTrace rating (as they never look and never will be able to look to the code quality, just push a bunch of “hello worlds” and you will have a good rating).</p><pre>function evil_laugh() {<br>    FNAME=$RANDOM<br>    DATE=$1<br>    export GIT_MERGE_AUTOEDIT=no<br>    for i in {1..4}<br>    do<br>        cp a.cpp ${FNAME}${i}.cpp<br>        git add ${FNAME}${i}.cpp<br>        git commit --amend --no-edit -m &quot;hi codetrace&quot; --date=&quot;${DATE} 20:00:00 2017 -0600&quot;<br>        git pull origin master<br>        git push origin master<br>    done<br>}</pre><p>You should just call evil_laugh passing some date, i.e. “Mar 19”, and it does push 4 times (4 is the minimum number of contributions to make the color deep green).</p><p>P. S. <a href="https://github.com/vardanator?tab=overview&amp;from=2017-12-01&amp;to=2017-12-31">Here’s my GitHub profile</a> if you want to see how nice does it look on a profile.</p><p>P. P. S. Hack around for other cool stickers, publish them with #githubartchallenge.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4c833c12bcf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Node.js V8 internals: an illustrative primer]]></title>
            <link>https://codeburst.io/node-js-v8-internals-an-illustrative-primer-83766e983bf6?source=rss-d2445cca3a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/83766e983bf6</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[v8]]></category>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Vardan Grigoryan (vardanator)]]></dc:creator>
            <pubDate>Sat, 11 Nov 2017 01:07:17 GMT</pubDate>
            <atom:updated>2022-07-24T09:20:13.257Z</atom:updated>
            <content:encoded><![CDATA[<p>When you switch from C++ to a more “friendly” language, you get this strange feeling of being fooled by this new language, its environment or its runtime, or something else (can’t tell you that). In C++ you have to think low (I mean low-level), go deeper, you have to understand [at least some] low-level details. As a matter of fact, you have to understand those details just to understand how your code works or could have worked (and then understand more in years to come and still be confused about how difficult it is to master such a language). Server-side JavaScript, Node.js, is really perfect for backend, actually, my experience with Node.js so far was just a REST API development (those nicely structured URLs with corresponding handlers, if this, then send that, else send this, mostly routine stuff). Node.js took my heart by its asynchronicity, and the part in me, the part who screamed about the greatness of C++ was always whispering those magic words, “but how? How does it work?”.</p><p>As a fan of C++ (that doesn’t mean I know it well enough), I loved the idea that Node.js is based on <strong>libuv</strong> (written in C) and <strong>V8</strong> (written in C++, well, for the most part). So it’s kind of easy to dig. Easy peasy, right? Easy.. peasy..</p><p>We gonna investigate (sort of) the JavaScript V8 engine.</p><blockquote>V8 is open source JavaScript execution engine, which provides a high performance execution environment for JS code.</blockquote><p>There are really tons of JS engines, I just like the idea of investigating a product produced by Google engineers. It&#39;s kind of a brand name, you see, the engine, it’s not V8, it’s Google’s V8. And why are we gonna dive deeper? Well, besides the fact that it’s really interesting to dig some proof of concept technology, it also will help us to write better code.</p><p>First of all, we need to compare the C++ compilation process with the Node.js interpretation process (from now on I will use JS and Node.js interchangeably). At first, I thought of JS as a “simple” scripting language with a single interpreter doing a routine translation job.</p><p>In C++ we got source code, the compiler compiles source code units into object files. Sure there is a pre-processing phase when a special program called preprocessor (I just think of it as a part of the compiler) makes the source code “ready” for compiling. So the source is being compiled into object code. Object code units. Lots of them. (Suppose we have a big enough project).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A2-5b7y8fICprzxlzEmp-A.png" /><figcaption>AoT Compiling and executing (simple abstraction)</figcaption></figure><p>This process is pretty complicated, those who want to dive deeper into compilation/translation technologies/techniques, it is suggested to read the <a href="https://www.amazon.com/Compilers-Principles-Techniques-Tools-2nd/dp/0321486811">Dragon book</a> (still I haven’t read it, I didn’t even start, though I’ve read the Contents section, the About section, the Acknowledgement section, well, as usual with all my books). During the compiling process, the compiler generates object code as its output, some pretty optimized object code (yes, the machine code). Some developers insist that the compiler optimizes and produces better code than the developer itself. I can’t argue with that.</p><p>So there goes the <strong>linker</strong>, which is another tool meant to combine those object files, doing some address relocations, symbol resolution, etc. (it’s easy to find more info on linkers, really advised to do so). The meaning of the linker is really important, it glues the generated object code units into one big file, <strong>the executable. </strong>The file could be run as a program. Program. Someone must run the program. Not the user, the user is just initiating the start by double-clicking on the corresponding icon. There is another tool, the <strong>loader</strong>. The loader does what its name says, just like Hurry hurries, the Loader loads. The contents of the executable file must be loaded into the virtual memory by the operating system (loader is the part of the OS). So the loader just copies our executable file contents into the virtual machine, sets the corresponding instruction pointer registers of the CPU to the starting routine (main function?), and voila, the program begins to run. (The most abstract description of a hard process). So no lookbacks, the code is already compiled, the code is fully machine code, generated for the particular machine architecture. No interpretation, the CPU just executes the instructions (machine code instructions) one by one (well, suppose we have a straight CPU). That’s why people started to name this compilation AoT compilation. Ahead of Time (AoT), like “there is no need to compile it now, but, yep, you did it ahead of time”. The opposite of this is for sure the popular JIT compilation. Just in Time (JiT), like “compile it when you need it”. It’s like some Nike slogan, Just Compile It!</p><p>So here’s how the Just in Time compilation (aka interpretation-compilation, or you might say intercompilation) works in my point of view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EO8M4jaW67A0hEwaByOh-w.png" /><figcaption>Just in Time compilation</figcaption></figure><p>Again, we have a source code (no preprocessing here, no C# allowed), and the source code is being interpreted by the interpreter. Remember Hurry? Hurry hurried, the interpreter interprets. An interpreter is a tool just meant to help the Virtual Machine. A virtual machine is a program that is being installed on a user&#39;s computer and supposed to run the code we write. In this particular case the “user’s computer” is our backend server, and the server runs our Node.js code. So the interpreter does not generate a machine code. It doesn’t need to know the different architectures/machines/platforms (Intel, AMD, Windows, Linux, …). The interpreter just needs to know about the virtual machine, well the virtual machine has to know about the architectures/machines/platforms. So the interpreter generates “code”, some “intermediate code” understandable by the virtual machine, and the virtual machine must generate the actual machine code to run the program. I thought it was just translating a higher-level code into a lower-level code line by line and executing each of it. Turns out, the interpreter and the virtual machine do some really tough stuff. Why so? Why not compile directly into a machine code? That’s a long story, a long and another story. The short answer is “the platforms”. There are so many…</p><p>Just cutting to the chase, interpreting is bad, compiling is good. Mm, more practically, interpreting is slow, and the execution of a compiled program is faster. But there are many other “bad” things about JavaScript particularly. First of all, the weak typing. C++ is a strictly typed language, JavaScript is weakly typed. What does that mean? That means we can be free.</p><p>Strict typing is good, at least for the compiler itself. The compiler must strictly know the corresponding types of variables. Why? Because the compiler has to generate code. It has to place those variables in the right places, allocate fixed-size boxes for them, and place them as optimized as possible. The compiler can’t afford to place a 4-byte integer into a 20-byte box just because it could be transformed into some string.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ok-0zpbthMW3T_Ts1BZ8zw.png" /><figcaption>Strict typing helps compiler to generate correct code</figcaption></figure><p>The compiler places variables exactly where they “should be”.</p><p>Instead of this, you can write something like this in JavaScript without any feeling of incompetence (a little).</p><pre>var some = &quot;this is a string&quot;; // declaring a string<br>some = 36; // change the type on the fly<br>some = 3.14; </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v_H6SJ5V6ERqFomHPWwmSw.png" /><figcaption>Weak typing slows down the execution</figcaption></figure><p>How should the interpreter interpret the variable ‘a’ above (sometimes I use interpreter, virtual machine, and execution engine interchangeably)? Should it place “a” in a large (just in case) box? Should store hidden variables for each of the “a”s types? Anything the interpreter (or virtual machine) will do to support these “language quirks”, will slow down the execution of the code.</p><p>There is more coming…</p><p>What about the objects that can “change” their properties dynamically, on the fly? See below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*phNbzyc5am5pK17r8unBrg.png" /><figcaption>Stress testing the virtual machine</figcaption></figure><p>All we care about is the object layout. See, the C++ compiler generates objects smoothly laid out, while JavaScript’s “execution engine” struggles on the thinking, how to “<a href="https://en.wikipedia.org/wiki/Frak_(expletive)">frakin</a>” do that?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g8Pd4Eh1Fmnk4QBsX-G_TA.png" /><figcaption>Object memory layout</figcaption></figure><p>I call these illustrations “pseudo-illustrations” as sometimes they contain some invalid but not significant details. In the illustration above we see that in C++, A’s instance is laid out “smoothly”, “a” property takes 4 bytes (just an assumption, like I said, pseudo-illustration) and starts from the address 0xA0. The object itself (A’s instance) starts at address 0xA0, so the first property, “a”, is placed at the address 0xA0 + the corresponding offset (0 in this case, as the “a” property, is the very first property of the instance). So as “a” takes 4 bytes, the next (2nd) property “b” starts at 0xA0 + 4 (the size taken by “a” property). “c” starts at 0xA0 + 12 (plus the size used by “a” and “b”). There is an aligning factor we omitted (not a major case in this context).</p><p>So now look at the right side of the same illustration. How should JS place an instance of A and its properties? How should it guess the type, what if they would change? What should it do? Where shall it go?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*sMNXACG6vLlJt9Ar." /><figcaption>V8, trying to execute your code as fast as it can</figcaption></figure><p>Finally, we got to the point, Hidden Classes. V8 introduced the idea of the hidden classes just to make the code execution faster. Faster than properties’ “dictionary lookup”. It’s done by generating hidden classes for each object instance you create plus some more. For instance, when we have code like this.</p><pre>function Foo(a, b) {<br>  this.a = a;<br>  this.b = b;<br>}</pre><p>We see a “struct” with two properties, while V8 sees pain in the…class. That’s because to execute new Foo(x, y); V8 has to create several hidden classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ogk5T4O_cS5eQ_xCGYCZJg.png" /><figcaption>V8 creates an empty hidden class for the object</figcaption></figure><p>When executing the first line of the Foo, V8 makes transition from hidden class __Foo0 to hidden class __Foo1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FVo0uCbXcsZvgG4oE4sEfA.png" /><figcaption>Execution of the first line adds the first property into the object, and makes a hidden class transition</figcaption></figure><p>The same logic applies to the execution of the second line (this.b = b;).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fNzgsvDOxkWPSibTKdk67A.png" /><figcaption>Adding the second property makes another transition, to __Foo2</figcaption></figure><p>The concept is okay. When V8 executes the new Foo(x, y)` it creates a hidden class. An empty hidden class. Something like this in C++.</p><pre>struct __Foo0 {};</pre><p>When V8 executes the first line, e.g. (creating) assigning the property “a”, it generates another hidden class and makes the so-called “transition” to a “newer version” of the __Foo0 hidden class.</p><pre>struct __Foo1 {<br>  Type a; //<br>};</pre><p>I intentionally left the Type of the “a” property unspecified (you might guess that based on the actual type another hidden class would be generated, tough times for V8, huh?).</p><p>Finally, the execution of the last line produces another, 3rd hidden class, something like this.</p><pre>struct __Foo2 {<br>  Type a; // I have offset 0, I&#39;m the first property, yay<br>  Type b; // I have offset 1, I&#39;m the second and unamused<br>};</pre><p>Why is this done so? Just because it’s faster than a simple dictionary lookup. V8 can treat our JS objects like C++ objects, with proper smooth memory layouts, with corresponding offsets for each property. This might add some overhead on the code size but indeed makes the code run faster. At least faster than before.</p><p>Hidden classes are also helpful in Inline Caching, another “trick” implemented in V8 (invented somewhere else). I’m unable to provide more info on Inline Caches, a topic I’ve just started to dig into, but here’s a sample code, where the hot function with corresponding Inline Caching applied would make some sense.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LRa1j_lGzA54S1mCOS6wcQ.png" /><figcaption>Hot function optimization, Inline Caching super-abstract intro</figcaption></figure><p>We have printFoo function, taking an object of type Foo discussed before. So this code above calls printFoo 3 times. With the same “declared” type of object, but as we already can see, with different hidden classes. The trick here’s that V8 optimizes function calls based on the input argument’s “kind”. When a function gets called several times (say, more than 2), then V8 starts to think about marking it as a “hot” function. “Hot” functions should be optimized as soon as it really possible, mostly because if the function is called many times, and if the function makes some load, then the load will be “applied” as many times as the function is called. Sounds simple. So by optimizing these “hot” functions V8 tries to reduce the code execution time. The actual optimization goes by profiling the function call and gathering required data on the “kind” of the passed argument. We pass obj , then we access both x and y properties of obj . So if the hidden classes of all passed objects are the same, V8 caches the call to the corresponding memory location of properties x and y (I might say something wrong here, be alert). In the code above we passed objects of different hidden classes. So if we would do something like this:</p><pre>printFoo({a: 1, b: 2});<br>printFoo({a: 2, b: 3});<br>printFoo({a: 44, b: 55});</pre><p>then these calls would be successfully optimized by V8. (this is some really artificial example, however it illuminates the idea).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iS6mb9HJt61McLwnHD9K5Q.png" /></figure><p>The previous illustration shows the simple idea, but how does the “is it hot?” check work? Turns out V8 makes some behavior analysis when a function is being called.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_b5p13b92C912uQoucyJ_w.png" /><figcaption>Optimized vs Unoptimized code execution</figcaption></figure><p>For each suspicious function call, some profiling data is being updated on that particular function. Before the next call “is it hot?” check is done. So if the function is hot, then the code execution switches to the optimization course. Optimization is done by another compiler, it generates an optimized machine code and updates the corresponding “execution context” with the optimized code.</p><p>We see in the illustration above that there are different names for two different compilers. Full-codegen for unoptimized machine code compiler and Crankshaft+TurboFan as optimized compiler. Actually, it was just Crankshaft, and as I got it from V8’s blog posts, Crankshaft wasn’t good enough for scaling. And it is being replaced by TurboFan and already or sooner (not sure yet) Crankshaft would be completely removed from V8. And then comes Ignition. Ignition is the V8’s interpreter, intended to replace the Full-codegen unoptimized compiler.</p><p>So far we got this double compiler idea. V8 generates some unoptimized machine code from our source JS and executes it. During this execution, V8 analyzes code behavior and collects some metadata. Then based on this metadata, V8 generates an optimized machine code making this optimized version as current running version. All of these mentioned couldn’t be done on a single thread. V8 uses different threads to manage this huge work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7AnDrzoBExxrZQ_fTDoaaQ.png" /><figcaption>Different threads for code execution</figcaption></figure><p>There is the main thread, used to run our code as soon as possible. And by “as soon as possible” I mean it takes time to parse the code, it takes time to generate corresponding machine code, and then the main thread starts to run it. Besides the main thread, there is another thread marked in the illustration as “optimizing compiler thread”. I put a “profiler thread” in the illustration just to make the picture complete. And there are some Garbage Collector threads just to keep all threads in a single illustration. So as the illustration shows, the main thread parses and runs our code. During this run, the optimizing compiler works to generate optimized machine code and replace “hot” parts of the code.</p><p>So, the full picture looks like this (I grabbed it from <a href="https://medium.com/dailyjs/understanding-v8s-bytecode-317d46c94775">Franziska Hinkelmann’s blog post about V8 bytecode</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*J5ebPSZ0oA9baK9fMD-yfA.png" /><figcaption>V8 compiler pipeline</figcaption></figure><p>As shown in the image above, the parser parses JS code into Abstract Syntax Tree, which is then being interpreted by Ignition (the interpreter). Ignition produces bytecode able to be executed instruction by instruction (compiling to unoptimized machine code). During the code, execution TurboFan works hard on the source code (working shoulder to shoulder with Ignition).</p><p>There are tons of information available on the web, and some of them are really important to read/watch (read them with me, I’ve just started to dive deeper into V8 implementation):</p><ul><li><a href="https://github.com/v8/v8/wiki/TurboFan">v8/v8</a></li><li><a href="https://github.com/v8/v8/wiki/Design-Elements">v8/v8</a></li><li><a href="https://v8project.blogspot.am/">V8 JavaScript Engine</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fr5OWCtuKiAk&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dr5OWCtuKiAk&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2Fr5OWCtuKiAk%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ab747db73d496d1d99bdec58f6222a0/href">https://medium.com/media/7ab747db73d496d1d99bdec58f6222a0/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FM1FBosB5tjM%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DM1FBosB5tjM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FM1FBosB5tjM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ad05754ce15ca50b6e33589835acf27/href">https://medium.com/media/7ad05754ce15ca50b6e33589835acf27/href</a></iframe><p>Also follow Benedikt’s blog: <a href="http://benediktmeurer.de/">http://benediktmeurer.de/</a></p><p>And my personal favorite: <a href="https://www.youtube.com/watch?v=p-iiEDtpy6I">https://www.youtube.com/watch?v=p-iiEDtpy6I</a></p><p>P. S. If you find any errors or you might add some improvement, please leave a comment, post author is not an expert in V8 internals.</p><figure><a href="http://bit.ly/codeburst"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i3hPOj27LTt0ZPn5TQuhZg.png" /></a></figure><blockquote>✉️ <em>Subscribe to </em>CodeBurst’s<em> once-weekly </em><a href="http://bit.ly/codeburst-email"><strong><em>Email Blast</em></strong></a><strong><em>, </em></strong>🐦 <em>Follow </em>CodeBurst<em> on </em><a href="http://bit.ly/codeburst-twitter"><strong><em>Twitter</em></strong></a><em>, view </em>🗺️ <a href="http://bit.ly/2018-web-dev-roadmap"><strong><em>The 2018 Web Developer Roadmap</em></strong></a><em>, and </em>🕸️ <a href="http://bit.ly/learn-web-dev-codeburst"><strong><em>Learn Full Stack Web Development</em></strong></a><em>.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83766e983bf6" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/node-js-v8-internals-an-illustrative-primer-83766e983bf6">Node.js V8 internals: an illustrative primer</a> was originally published in <a href="https://codeburst.io">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>