Sunday, February 24, 2019

Coding Interview: The Game Plan

I am doing interviews few times a year, and it's probably not enough[1]. Opportunities aside, I learn a valuable lesson every time.
Interview pressure uncovers weaknesses. Mine are overcomplication, impatience and panic:
  • I somehow expect the problem to be hard. So, I dismiss valuable cues and intuitions if they look too obvious.
  • If I feel a hunch, I dive in without full understanding. I keep stepping on this rake... and solving a wrong problem!
  • I the problem sounds intimidating, I panic and freeze, not knowing where to start.

Brute-force

To compensate for these weaknesses, I now start with a simplest solution that comes to mind. I work on a naïve solution first, clarifying my understanding, and then brainstorm ideas to improve it.
Structuring your work this way reduces the cognitive load when you start working on an improved solution.
This is an intuitive and well-recommended technique. However, I feel that candidates are afraid to look inexperienced and skip this step. As an interviewer, you may want to offer your candidate to start easy.
image

The Game Plan

It helps to mentally structure the interview into phases. The opening is important as it sets the tone, and brute-force can help you get through. Early phases are head-up: collaborate, learn and explore. Late phases are head-down: focus and deliver.
The game plan also helps manage your time and deliver a solution before the interview is over.

Monday, February 18, 2019

Interview Pearls: K Consecutive Bit Flips

This is a cool problem that sounds very hard by becomes easy with two intuition sparks (and a little twinkle).

Description

In an array A containing only 0s and 1s, a K-bit flip consists of choosing a (contiguous) subarray of length K and simultaneously changing every 0 in the subarray to 1, and every 1 in the subarray to 0.
Return the minimum number of K-bit flips required so that there is no 0 in the array. If it is not possible, return -1.

Example

Input: A = [0,0,0,1,0,1,1,0], K = 3
Output: 3
image

Sunday, February 10, 2019

Interview Pearls: Sliding Window

If the problem talks about continuous subarrays or substrings, the sliding window technique may help solve it in a linear time. Such problems are tricky, though the solution is simple once you get it. No wonder I am seeing such problems in almost every interview!
Here, we will take a look at Subarrays with K Different Integers (LeetCode Hard), which appeared on LeetCode weekly contest #123. You can also master the sliding windows technique with these additional problems:

Problem Description

Given an array A of positive integers, call a (contiguous, not necessarily distinct) subarray of A good if the number of different integers in that subarray is exactly K. For example, [1,2,3,1,2] has 3 different integers: 1, 2, and 3.
Return the number of good subarrays of A.

Example

Input: A = [1,2,1,2,3], K = 2
Output: 7
Explanation: Subarrays formed with exactly 2 different integers: [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2].

Sunday, January 27, 2019

Dynamic Programming: Minimum Travel Cost

The higher is the bar, the more you're expected to use dynamic programming (DP) during an interview. This technique requires a lot of practice to grasp; if you've mastered the recursion, DP is the next level.
This problem appeared on LeetCode weekly contest #121, and it's a good problem to practice the DP thinking.

Problem Description

In a country popular for train travel, you have planned some train travelling one year in advance. The days of the year that you will travel is given as an array days. Each day is an integer from 1 to 365.
Train tickets are sold in 3 different ways:
  • 1-day pass is sold for costs[0] dollars;
  • 7-day pass is sold for costs[1] dollars;
  • 30-day pass is sold for costs[2] dollars.
The passes allow that many days of consecutive travel. For example, if we get a 7-day pass on day 2, then we can travel for 7 days: day 2, 3, 4, 5, 6, 7, and 8.
Return the minimum number of dollars you need to travel every day in the given list of days.

Tuesday, July 3, 2018

Coding Interview: Pseudocode

"Interview is an artificial reality designed by companies to keep people out" - Manager Tools
Many companies won't offer helpful feedback on your interview performance. I think that feedback is a fair game, and the process should be transparent.

Pseudocode

This is a follow-up on the older post, Interview Insider: Coding fluency. A reader asked my opinion on using pseudocode to document his thoughts while working on the solution. Specifically during a phone screening, when diagramming may not be a possibility.
I want to start by quoting Steven Skiena's TADM[1]:

Tuesday, May 8, 2018

Productivity Tips: Git merge

If some rather mindless activity takes 20 minutes out of your day on most days, it’s a big deal. That's two weeks in a given year you would rather spend in Hawaii. For a medium-size team, improving the productivity to save these 20 minutes is like hiring one more developer.

Efficient Git merge


I am still new to Git, and I am really liking it. The workflow I learnt from tutorials was to create a local master branch and another local branch for a pull request. To get new changes or resolve conflicts, you switch to the local maser branch, pull it, switch to the other branch, and merge from the local master branch.

The problem here is that Visual Studio reloads the solution when you switch branches. For the solution with ~100 projects, it took up to 3 minutes, times two as you need to switch back to the other branch.
I felt there must be a better way, but for several months I stuck to what I knew. To my surprise, many of my teammates (seasoned folks) were doing the same. This tip allowed merging without switching the branch, which made our day more productive and enjoyable.

Thursday, April 13, 2017

Coding Interview: Coding fluency

"Interview is an artificial reality designed by companies to keep people out" - Manager Tools
Many companies won't offer helpful feedback on your interview performance. I think that feedback is a fair game, and the process should be transparent.

Coding fluency

Coding fluency is how quickly you translate your solution into code. Though I measure the time (with a stopwatch), coding fluency is not as important to me as other criteria [1]. Most good companies, however, have their bar set very high on coding fluency.

I saw weak candidates rapidly producing a lot of code, and very strong candidates who needed help getting going. In the end, a person who quickly wrote the initial implementation may spend a lot of time getting it right, and a candidate who took extra 10 minutes to think it through may come up with an elegant solution.
People are nervous during the interview. Many experience a blank page syndrome, or a writer's block when staring at that whiteboard. Candidates who deal with more than one language or discipline may feel rusty due to the context switching. I just recently experienced a block, panicked and then wrote messy code. I attribute it (or I hope so) to 6 months of doing web front-end development.

Sunday, April 9, 2017

Interview Pearls: Interleave array in-place

I got this problem in the real interview, and I thought it was interesting. I used the divide and conquer paradigm and came up with a linearithmic solution. After the interview, I could not help thinking about potential linear solution. Read on to see what I found with a little help from the number theory.

Problem Statement

"Given array [a1, a2, ..., an, b1, b2, ..., bn], interleave it in-place to [a1, b1, a2, b2, ..., an, bn]"
This problem is also known as "in-shuffle". Think about cutting a deck of cards into equal halves, and interleaving them perfectly, like some of poker junkies can do. It's easy to solve this problem in linear time if you can use additional memory, but the point here is to do it in-place.

Friday, March 10, 2017

Interview Pearls: Count Inversions (Expert)

I am collecting problems that start easy and then lead to a deep conversation, touching on multiple aspects of computer science fundamentals. These problems are being asked during interviews in the top technology companies, often with a twist to see if you understand the underlying principles and can adapt your solution.

Part 1: Introduction, coding practice and simple solutions
Part 2: Advanced solutions
Part 3: Expert solutions

Here we have an innocent-looking problem that bled me dry (luckily, it was not in a real interview!). Turned out, there are many interesting ways to solve it, and I thought it could be a good illustration to some fundamental algorithms. If you digested advanced solutions OK, here is the desert menu: segment tree, lazy propagation segment tree, and height-balanced BST with counters.

7. Segment tree

Segment tree has the same purpose as binary indexed tree (BIT) - efficiently sum ranges in a mutating array. Go ahead and review solution #5 in the previous post to see how we combine update and sum operations to count inversions.

I used to confuse segment tree with interval tree, but they are quite different. Interval tree stores arbitrary intervals in binary search tree, so it can find an overlap in a logarithmic time. Segment tree always works with a predefined interval, which is the size of the underlying array, and uses logarithmic segments of that interval to efficiently perform range operations.

Segment tree is an actual binary tree (unlike BIT); leaves represent elements of the array, and parent nodes represent segments of the array, storing the operation result of its children (and therefore all elements in the segment). Because of that, segment tree requires additional memory comparing to BIT, but also supports non-cumulative operations, such as minimum or maximum value in the range.

Friday, March 3, 2017

Interview Pearls: Count Inversions (Advanced)

I am collecting problems that start easy and then lead to a deep conversation, touching on multiple aspects of computer science fundamentals. These problems are being asked during interviews in the top technology companies, often with a twist to see if you understand the underlying principles and can adapt your solution.

Part 1: Introduction, coding practice and simple solutions
Part 2: Advanced solutions
Part 3: Expert solutions

Here we have an innocent-looking problem that bled me dry (luckily, it was not in a real interview!). Turned out, there are many interesting ways to solve it, and I thought it could be a good illustration to some fundamental algorithms. In the previous post, I covered introductions and simple (but not very efficient) solutions. This is the fun part - we will use advanced concepts like self-balancing trees, binary index trees, and the divide and conquer strategy.

4. Self-balancing BST with counters

So, we implemented our very own BST that can efficiently tell us how many elements are smaller than any given value (solution #3 in the previous post). The run-time complexity is O (n * h), where h is the height of the tree. For a balanced tree, the height is log n, so the complexity is linearithmic. In an unbalanced tree the height can grow up to n, resulting in the quadratic time.

To fight the quadratic time, we can balance the tree to keep its height proportional to log n [1] by performing tree rotations when inserting new elements. Tree rotations require amortized [2] constant time, so the overall run-time will be still linearithmic. We need to extend our previous solution with the rotation operations and track the number of elements in the both left and right subtrees (so that we can efficiently recalculate these numbers after the rotation).

Tuesday, February 28, 2017

Interview Pearls: Count Inversions

I am collecting problems that start easy and then lead to a deep conversation, touching on multiple aspects of computer science fundamentals. These problems are being asked during interviews in the top technology companies, often with a twist to see if you understand the underlying principles and can adapt your solution.

Part 1: Introduction, coding practice and simple solutions
Part 2: Advanced solutions
Part 3: Expert solutions

Here we have an innocent-looking problem that bled me dry (luckily, it was not in a real interview!). Turned out, there are many interesting ways to solve it, and I thought it could be a good illustration to some fundamental algorithms. In this first post, we will start with three relatively simple (but not very efficient) solutions. In later parts, we fiddle with binary search trees, indexed trees, merge sort, and even segment trees.

Problem Statement

"Given an array of numbers, count pairs where i < j and numbers[i] > numbers[j]"
I saw this problem also referenced as "Reverse Pairs" and "Count of Smaller Numbers After Self". The result indicates how far the array is from being sorted. It's zero if the array is already sorted, and it's maximum (1 + 2 + ... + size - 1, or size * (size - 1) / 2) if it's sorted in the reverse order. Another way to look at this; the result is the number of swap operations required to sort the array using the bubble sort algorithm.

Friday, February 17, 2017

Graph databases and rapid prototyping (part 3)

In this last part, I am comparing the development experiences when using SQL Server and Neo4j graph database. There is also an overview of Neo4j tools and functionality, and how they accelerate web development and prototyping.

Part 1: How I got hooked on graph databases
Part 2: What is a graph database
Part 3: Rapid prototyping
"Java and Javascript are similar like Car and Carpet are similar" - fun fact
Now when I think about it, a graph database feels like a dynamically-typed language, and a SQL database - like a statically-typed one. As you would consider a dynamically-typed language, such as JavaScript, for the web development and prototyping, a graph database is also a good option for these cases.

"If all you have is a hammer, everything looks like a nail" - the law of the instrument
We have successfully used SQL Server on many projects, and it was our default database choice. For our recent web application, it required a good amount of design and plumbing before we can expose data through Web API. As requirements refined, our initial design underwent many changes. Even with good tools and automated steps, it was painful and time-consuming making changes to the data schema, and, despite 2 abstraction layers, the app was often broken afterwards.

Thursday, February 9, 2017

Graph databases and rapid prototyping (part 2)

In this part, I am providing a brief explanation of what a graph database is, with some examples on the data modeling and querying. I am also talking about the schema-less nature of the graph databases, and what advantages it provides when you just start your project.

Part 1: How I got hooked on graph databases
Part 2: What is a graph database
Part 3: Rapid prototyping
"Fool tidies up, a genius rules over chaos" - Albert Einstein

A graph database looks like a bunch of nodes with properties (key-value pairs) and relationships between them. Imagine you gathered data from multiple sources about people, their tweets, posts, likes, friend and followers. Each node may have some unique properties, and there could be similarities.
Rihanna is a friend with the monster, and she likes his posts
Similar nodes can be categorized using labels, such as "person", "monster" and "post". Relationships can have labels too, like "friend", "likes" and "publishes".

Wednesday, February 8, 2017

Blog ideas

I planned to make a to-do list, or a Kanban board or something, but having it as a blog post provides an important advantage - an extra blog post. Plus, I can see it one place, and give the opportunity for my mom (who does not speak English) and my wife (who does not care about programming) to see what's hopefully coming.


  1. Schema-less graph databases
    How I got hooked, and how it changed my approach to design software.
  2. Algorithms - Dynamic Programming - Buy/Sell Stock I, II, III, IV, V, and VI.
    Great problem - it starts easy and gradually gets very complex, showing the power of dynamic programming. It's described in a few books and blog posts, and I think there is a value in bringing it all together and build more complex solutions on top of easier ones, like an elephant pyramid.
  3. NUTR 200
    I just finished this course in University of Washington, and I had few insights worth sharing, like why a fat-burning exercise has to be more than 20 minutes long.
  4. Programming interview from the other side
    I helped interviewing college and industry candidates for my company. I thought I'd describe my approach to evaluate candidates, and criteria we used to compare their performance.
  5. Programming Interview Pearls
    These algorithms are being asked during the interviews. They may seem easy, but they can get very deep. With many of them, there is often an 'aha' moment, leading to an elegant and simple solution. 
Upcoming posts and pages:

Why blogging?

"Learn one, do one, teach one"
The main reason I want to do this is to practice writing. The second is to organize some of my learning in my own head. It's also a good practice doing something consistently over a prolonged period, which is hard for me to do.

I was inspired to start a blog mostly by John Sonmez and his Soft Skills: The software developer's life manual. The basic idea is that, to be a teacher, you just need to be one step ahead. Even more, teacher who is too far ahead may have forgotten how hard it was to learn something in the beginning. So, if you are somewhere in the middle, you have the biggest audience you can be the best teacher for.

I like term "coach" better than "teacher". Anyone can coach anyone . It's just a matter of giving your attention and consideration, and it is liberating.

Tuesday, February 7, 2017

Graph databases and rapid prototyping (part 1)

In the first part, I'll tell you how I was forced out my comfort zone (SQL Server), and look for alternatives in the graph database space. I choose Neo4j, and I was surprised how easy it was to use, and how productive I became.

Part 1: How I got hooked on graph databases
Part 2: What is a graph database
Part 3: Rapid prototyping

I am very excited to share tremendous experience I had with graph databases (Neo4j specifically), and how going schema-less first (and hybrid or schema-full later) changed my approach to design software. This topic is orthogonal to "NoSQL", the term that holds the second place ("cloud" being the first) in overuse and ambiguity.

For many years, my "to go" (and only) option to do any database work was Microsoft SQL Server. It was easy and natural to open Management Studio and start writing SQL queries. Plus, vast and mature tooling, integration options, language support, community and documentation... you name it.