Solving a classic interview problem with Go
Programming Snapshot – Go Slices
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.
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.
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
connected.go
01 package main 02 03 import ( 04 "fmt" 05 ) 06 07 const ( 08 Green = iota 09 Blue 10 Red 11 ) 12 13 type pos struct { 14 x int 15 y int 16 } 17 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]) 26 27 // create 2D-array with same dimensions 28 seen := make([][]bool, rows) 29 for i := range seen { 30 seen[i] = make([]bool, cols) 31 } 32 33 max := []pos{} 34 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 } 44 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
explore.go
01 package main 02 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] 08 09 for len(examine) > 0 { 10 curpos := examine[0] 11 examine = examine[1:] 12 13 if seen[curpos.x][curpos.y] { 14 continue 15 } 16 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 } 26 27 return results 28 }
Buy this article as PDF
(incl. VAT)
Buy Linux Magazine
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.
News
-
New Slimbook EVO with Raw AMD Ryzen Power
If you're looking for serious power in a 14" ultrabook that is powered by Linux, Slimbook has just the thing for you.
-
The Gnome Foundation Struggling to Stay Afloat
The foundation behind the Gnome desktop environment is having to go through some serious belt-tightening due to continued financial problems.
-
Thousands of Linux Servers Infected with Stealth Malware Since 2021
Perfctl is capable of remaining undetected, which makes it dangerous and hard to mitigate.
-
Halcyon Creates Anti-Ransomware Protection for Linux
As more Linux systems are targeted by ransomware, Halcyon is stepping up its protection.
-
Valve and Arch Linux Announce Collaboration
Valve and Arch have come together for two projects that will have a serious impact on the Linux distribution.
-
Hacker Successfully Runs Linux on a CPU from the Early ‘70s
From the office of "Look what I can do," Dmitry Grinberg was able to get Linux running on a processor that was created in 1971.
-
OSI and LPI Form Strategic Alliance
With a goal of strengthening Linux and open source communities, this new alliance aims to nurture the growth of more highly skilled professionals.
-
Fedora 41 Beta Available with Some Interesting Additions
If you're a Fedora fan, you'll be excited to hear the beta version of the latest release is now available for testing and includes plenty of updates.
-
AlmaLinux Unveils New Hardware Certification Process
The AlmaLinux Hardware Certification Program run by the Certification Special Interest Group (SIG) aims to ensure seamless compatibility between AlmaLinux and a wide range of hardware configurations.
-
Wind River Introduces eLxr Pro Linux Solution
eLxr Pro offers an end-to-end Linux solution backed by expert commercial support.