Solving a classic interview problem with Go

Programming Snapshot – Go Slices

© Lead Image © bowie15, 123rf

© Lead Image © bowie15, 123rf

Article from Issue 236/2020

Springtime is application time! Mike Schilli, who has experience with job application procedures at companies in Silicon Valley, digs up a question asked at the Google Engineering interview and explains a possible solution in Go.

The TechLead [1], Patrick Shyu, is a YouTube celebrity whose videos I like to watch. The former Google employee, who has also completed a gig at Facebook, talks about his experiences as a software engineer in Silicon Valley in numerous episodes on his channel (Figure 1). His trademark is to hold a cup of coffee in his hand and sip it pleasurably every now and then while he repeatedly emphasizes that he's the "tech lead." That's how Google refers to lead engineers who set the direction for the other engineers on the team. The first-line managers there traditionally stay out of technical matters and focus primarily on staffing and motivating their reports.

Figure 1: On his YouTube channel, TechLead Shyu blusters about the daily grind in Silicon Valley.

One episode on the TechLead channel is about typical questions asked at interviews at Google, of which the former employee says he has conducted hundreds. In this Snapshot issue, we'll tackle one of the quiz questions that he allegedly invented himself and kept asking, a slightly modified version of the flood fill problem [2]. The latter is so well-known that by now any candidate can rattle off the solution blindfolded. That's why Google has removed it from the list of questions, and the TechLead created his own version [3].

Vague Question

The candidate's only clues to the puzzle are a diagram drawn on a whiteboard with 12 tiles (Figure 2). They are arranged in three rows and four columns and are colored in green, blue, or red. The task now is to write a program that determines the most connected tiles with the same coloring.

Figure 2: Which set of adjacent tiles is the largest?

As always in a job interview, the first step is to find out what the interviewer, who often deliberately asks vague questions, actually has in mind. In this case it is not quite clear what "connected" really means: Is the blue square in the third column of the first row connected to the diagonally "connected" squares below it or not? When asked, the interviewer confirms that connected tiles must share a whole side with their partner. The sixth blue tile at the top in Figure 2 is therefore not part of the U-shaped compound of five blue tiles below. But they still form the largest group in the diagram, so the algorithm needs to output their coordinates at the end.

Creating a Model

To tackle this problem, a viable candidate first would create a data model. Since the algorithm later handles X/Y coordinates as a unit, the type definition in line 13 of Listing 1 [4] bundles tile locations, denoted in integer coordinates, x and y, into a type named pos (for position). A two-dimensional array then describes the grid, with integer values representing the colors green, blue, and red for individual tiles. The const statement starting on line 7 automatically enumerates these as the constants  , 1, and 2, thanks to the iota keyword after the first element.

Listing 1


01 package main
03 import (
04   "fmt"
05 )
07 const (
08   Green = iota
09   Blue
10   Red
11 )
13 type pos struct {
14   x int
15   y int
16 }
18 func main() {
19   tiles := [][]int{
20     {Green, Green, Blue, Red},
21     {Green, Blue, Red, Blue},
22     {Red, Blue, Blue, Blue},
23   }
24   rows := len(tiles)
25   cols := len(tiles[0])
27   // create 2D-array with same dimensions
28   seen := make([][]bool, rows)
29   for i := range seen {
30     seen[i] = make([]bool, cols)
31   }
33   max := []pos{}
35   for x, row := range tiles {
36     for y, _ := range row {
37       connected := explore(tiles,
38         pos{x, y}, seen)
39       if len(connected) > len(max) {
40         max = connected
41       }
42     }
43   }
45   fmt.Printf("Largest Group: %v\n", max)
46   dump(tiles, max)
47 }

Line 19 then defines a two-dimensional array slice, which in Go is a slice of slices. Three sub-slices with four elements each form the rows of the matrix (starting with the first row and its tiles Green, Green, Blue, Red). To access an individual tile, tiles[i][j] first uses i to reference the row slice and then the element at column position j within that slice.

The x coordinates therefore run from top to bottom in the matrix (starting with zero), and the y coordinates from left to right. For example, accessing tiles[2][3] selects the tile bottom right. Thanks to slice literals in Go, Listing 1 can initialize the contents of the entire data structure from line 19 directly in the curly brackets without having to worry about explicit sub-slice allocations.

Another data structure is created from line 28 onwards in the form of the seen variable. When browsing the matrix later on, the algorithm makes a note of the tiles it has already covered, avoiding unnecessary work or getting stuck in endless loops. To this end, it uses a helper structure, consisting of another two-dimensional slice of Boolean values. In a scripting language, it would probably be trivial to simply create another matrix with the same dimensions and fill it with Boolean types, but Go requires some extra steps because of its strict typing.

Line 28 first uses make() to allocate an array of Boolean slices, to match the number of rows in the tiles data structure. Then the for loop uses range from line 29 to iterate over the previously created rows and assign a Boolean slice to each corresponding to the number of columns of the original matrix in cols.

Once initialized in this way, the structure lets you use seen[x][y] to query whether the program has already seen the tile at position x and y. Thanks to the so-called "zero values" for undefined variables in Go, the individual Boolean values are preset to false right away – this saves the programmer the initialization.

Tracking the Max

As a result, the algorithm will later print a list of coordinates where the largest contiguous group's tiles are located. Line 33 defines the max variable, a slice type composed of pos structures that were previously declared at X/Y coordinates in line 13. The slice literal's curly brackets initialize the variable to create an empty slice initially.

The pair of for loops in lines 35 and 36 iterates over the rows and columns of the tile matrix and calls the explore() function on each element. It passes along the matrix itself, the position of the current element, and the seen tracker, in which the function highlights elements it has already visited to be able to skip them on subsequent calls. Starting with the current element, explore() sets out to find matching nearby elements and might cover entire areas that way. But the main program doesn't need to keep track, because even if the for loops stubbornly scan every element, the next call to explore() will immediately determine whether an element has already been scanned and ignore it in a flash if it finds out that's true.

The explore() function defined in Listing 2 returns a slice of coordinates containing tiles that are both connected to the given tile and have the same coloring. If the resulting list is longer than the one previously stored in max, line 40 of Listing 1 with the newly found, longer list. At the end of the program, line 45 only needs to output the longest list found so far and call the dump() function shown later in Listing 4, which outputs the result in a nice ASCII diagram (Figure 3).

Listing 2


01 package main
03 func explore(tiles [][]int, p pos,
04   seen [][]bool) []pos {
05   results := []pos{}
06   examine := []pos{p}
07   color := tiles[p.x][p.y]
09   for len(examine) > 0 {
10     curpos := examine[0]
11     examine = examine[1:]
13     if seen[curpos.x][curpos.y] {
14       continue
15     }
17     if tiles[curpos.x][curpos.y] ==
18       color {
19       results = append(results, curpos)
20       seen[curpos.x][curpos.y] = true
21       examine = append(examine,
22         neighbors(tiles,
23           pos{curpos.x, curpos.y})...)
24     }
25   }
27   return results
28 }
Figure 3: The algorithm has found the largest contiguous group and highlighted it in the grid.

Buy this article as PDF

Express-Checkout as PDF
Price $2.95
(incl. VAT)

Buy Linux Magazine

Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content

  • Cave Painter

    While searching for a method to draw geodata right into the terminal, Mike Schilli discovers the wondrous world of map projections.

  • ReportLab and Panda3D

    A game of bingo illustrates how to use the ReportLab toolkit and Panda3D real-time 3D engine.

  • Amazed

    Mazes fascinated even the ancient Greeks. Mike Schilli uses his Go programming skills to create a maze and then efficiently travel through it.

  • A taste of tiling with X-Tile
  • Tiling Desktops

    Tiling desktops have been experiencing a resurgence in popularity. Here are a few options that can help keep your desktop better organized.

comments powered by Disqus
Subscribe to our Linux Newsletters
Find Linux and Open Source Jobs
Subscribe to our ADMIN Newsletters

Support Our Work

Linux Magazine content is made possible with support from readers like you. Please consider contributing when you’ve found an article to be beneficial.

Learn More