To help you ace your Google coding interview, we’ve put together this guide. We give you an overview of what to expect, plus the topics you’re most likely to encounter and example questions from real candidates. We also recommend an effective answer framework and a simple prep plan.
Whether you’re applying for software engineer, engineering manager, machine learning engineer, site reliability engineer, data engineer, or other technical roles at Google, you’ll find this guide a great place to start with your prep.
- What to expect
- Google coding interview question examples
- How to answer Google coding interview questions
- Google coding interview preparation plan
Let’s get started!
1. What to expect
Let’s first look into a couple of details about Google coding interviews: when you’ll face them, and how they work at Google, specifically.
1.1 When will you face a coding interview?↑
If you’re applying for an engineering role at Google, you can expect to face coding questions at different stages of the interview process:
- Online assessment: most engineering candidates report getting a few coding challenges
- Phone screens: 1-2 sessions, 30- to 60-minute coding problem per session
- Onsite interviews: 3 coding interview rounds, 45-minute coding problem per round
If you’re applying for the engineering manager role, you may get asked to do a code review instead of a coding challenge during your onsite interview.
1.2 How coding interviews work at Google↑
The success of Google as an organization is driven by its strong engineering culture, and the standard of coding is second to none.
As a result, it's essential for all of the company's new engineers to have strong foundational coding skills.
That doesn’t mean you’re expected to get perfect marks during your coding interviews.
Here are the four main attributes that Google is on the lookout for during your coding rounds and the rest of your interviews:
- General cognitive ability. This is often referred to as "GCA" by Googlers. The company wants to hire smart engineers who can learn and adapt to new situations, including unfamiliar coding problems. Here your interviewer will try to understand how you solve hard problems and how you learn. For more information, take a look at our guide to the GCA interview.
- Role-related knowledge and experience. This is often referred to as "RRK" or "RRKE" internally. The company wants to make sure that you have the right experience, domain expertise and technical competencies for the position you're applying for. For more information, take a look at our guide to the RRK interview.
- Leadership. Google looks for a particular type of leadership called “emergent leadership.” You'll typically be working in cross-functional teams at Google, and different team members are expected to step up and lead at different times in the lifecycle of a project when their skills are needed. During your coding interviews, you’ll be assessed not just on your thought process but your ability to communicate it clearly. More information on this topic is in our guide to Google leadership questions.
- Googleyness (i.e. culture fit). During your coding interview, interviewers want to see if you exhibit the following values: being comfortable with ambiguity, having a bias to action, and having a collaborative nature. More information on this topic is in our guide to Googleyness questions.
A few more reminders during your coding interviews:
- You won’t have access to a compiler or IDE during your interview. So during practice, it’s best to get used to writing code on Google docs or a whiteboard.
- Time yourself during your coding practice. You’ll be given only a few minutes to solve a coding problem during your interview. Incorporate a timer when practicing so you get used to solving coding problems as fast as you can.
- For code reviews, take note of your language. If you’re an EM candidate and get a code review round, be sure to demonstrate Googleyness when you write your comments on the code. Provide positive feedback for a good line of code. Address problems and issues in a clear, concise, and respectful manner.
Now that you have an idea about how coding interviews work at Google, let’s take a look at the problems you may encounter.
2. Google coding interview question examples↑
According to Google SWE candidates on Glassdoor, Google typically gives Leetcode-style coding problems. They tend to level up in difficulty as you progress through the interview process.
This means you could expect easy LC questions during your online assessment and then move on to medium to difficult coding problems in your phone screens and onsite interviews.
The general advice is to practice with the top 50 latest Google-tagged problems on Leetcode.
Google also sends review materials and has a whole page dedicated to practice coding questions.
Based on our analysis of the 100 most recent SWE coding questions reported on Glassdoor, here are the most commonly asked coding topics at Google. We’ve also included the frequency they’re asked.
- Arrays & Strings: 42.9%
- Graphs & Trees: 33.7%
- Dynamic Programming: 11.2%
- Recursion: 6.1%
- Math: 6.1%
Let’s take a look at each DSA topic, plus some coding question examples from real candidate reports.
2.1 Arrays & Strings↑
An array is a list-like data structure that contains a collection of values, each associated with a specific index, usually with a fixed overall size. Arrays are one of the most fundamental data structures in programming and computer science, and many more complex data structures are built using arrays.
A string is an ordered sequence, or string, of characters. It is usually considered a data type and is often included as part of language primitives. In most languages, strings are implemented using an array of bytes. The bytes are encoded using some character encoding. Earlier systems used ASCII encoding, with Unicode encoding used in later systems.
Arrays and strings are two of the most fundamental data structures used in coding. Google asks questions related to these two topics to discern if you’ve got strong foundational skills.
Here are some example questions reported by SWE candidates on Glassdoor:
Google coding interview example questions: arrays & strings
- Implement Trie for prefix matching (Solution)
- Write a function to merge two sorted arrays without using extra space (Solution)
- Given an array of integers, return all unique triplets [a, b, c] where a + b + c = 0. Ensure no duplicate triplets in the output. (Solution)
- Write a function that prints out every permutation of 1s and 2s that add up to a number n. (Solution)
- Implement a Snapshot Array that supports pre-defined interfaces (note: see link for more details). (Solution)
- In a row of dominoes,
A[i]
andB[i]
represent the top and bottom halves of thei
-th domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.) We may rotate thei
-th domino, so thatA[i]
andB[i]
swap values. Return the minimum number of rotations so that all the values inA
are the same, or all the values inB
are the same. If it cannot be done, return-1
. (Solution) - Your friend is typing his
name
into a keyboard. Sometimes, when typing a character c, the key might get long pressed, and the character will be typed 1 or more times. You examine thetyped
characters of the keyboard. ReturnTrue
if it is possible that it was your friend's name, with some characters (possibly none) being long pressed. (Solution) - Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). (Solution)
- Given a list of query words, return the number of words that are stretchy. Note: see link for more details. (Solution)
- Given an array of words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified. (Solution)
- Given an encoded string, return its decoded string. (Solution)
Check out our guides on array interview questions and string interview questions to learn more about the topics.
2.2 Graphs & Trees↑
Graphs and trees are both abstract data structures fundamental to computer science. Both are represented by nodes (also known as vertices) connected by edges.
The main difference between the two is that trees represent a hierarchical relationship between nodes, while the relationship of nodes in graphs is arbitrary.
Similar to arrays and strings interview questions, Google coding interviewers asked graphs and trees questions to assess your foundational skills.
Here are some example questions reported by SWE candidates on Glassdoor:
Google coding interview example questions: graphs & trees
- Implement a cleaning algorithm for a robot vacuum cleaner that doesn't know its position within the room. (Solution)
- Write a code to construct a binary tree that is a mirror of the given binary tree. (Solution)
- Find the lowest common ancestor of two nodes (Solution)
- Write a function to detect cycles in a directed graph. How would you optimize a database query to improve runtime? (Solution)
- Given a binary tree, find the maximum path sum. The path may start and end at any node in the tree. (Solution)
- We can rotate digits by 180 degrees to form new digits. When 0, 1, 6, 8, 9 are rotated 180 degrees, they become 0, 1, 9, 8, 6 respectively. When 2, 3, 4, 5, and 7 are rotated 180 degrees, they become invalid. A confusing number is a number that when rotated 180 degrees becomes a different number with each digit valid.(Note that the rotated number can be greater than the original number.) Given a positive integer
N
, return the number of confusing numbers between1
andN
inclusive. (Solution) - Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that: 1) Only one letter can be changed at a time and, 2) Each transformed word must exist in the word list. (Solution)
- Given a matrix of N rows and M columns. From m[i][j], we can move to m[i+1][j], if m[i+1][j] > m[i][j], or can move to m[i][j+1] if m[i][j+1] > m[i][j]. The task is: print longest path length if we start from (0, 0). (Solution)
-
Given a robot cleaner in a room modeled as a grid. Each cell in the grid can be empty or blocked. The robot cleaner with 4 given APIs can move forward, turn left or turn right. Each turn it made is 90 degrees. When it tries to move into a blocked cell, its bumper sensor detects the obstacle and it stays on the current cell. Design an algorithm to clean the entire room using only the 4 given APIs shown below. (Solution)
Check out our guides on graph interview questions and tree interview questions to learn more about the topics.
2.3 Dynamic Programming↑
Dynamic programming (DP) is an algorithmic paradigm to create optimal solutions for complex problems by breaking them down into simpler sub-problems that can be solved recursively.
Dynamic programming methods are applicable to problems that have the following two properties:
- Optimal substructure: the optimal solution builds on the optimal solutions of smaller pieces.
- Overlapping sub-problems: the broken-down versions of the problem are repeated.
Some candidates on Glassdoor explicitly say that they were not asked DP questions, though there are quite a few who reported getting them.
DP questions do take longer to set up and solve, so most companies might not ask them. But since real Google candidates have reported getting them, it’s best to still include them in your prep.
Google coding interview example questions: dynamic programming
- Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0. (Solution)
- Find the minimum number of coins needed for change. (Solution)
- Non-overlapping intervals (Solution)
- Given a
matrix
and atarget
, return the number of non-empty submatrices that sum to target." (Solution) - Given a rows x cols binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area. (Solution)
- Your car starts at position 0 and speed +1 on an infinite number line. (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse)...Now for some target position, say the length of the shortest sequence of instructions to get there. (Solution)
- Given strings
S
andT
, find the minimum (contiguous) substringW
ofS
, so thatT
is a subsequence ofW
. If there is no such window inS
that covers all characters inT
, return the empty string""
. If there are multiple such minimum-length windows, return the one with the left-most starting index. (Solution)
2.4 Recursion↑
Recursion is a process wherein you make a function call itself directly or indirectly. It is one of the most fundamental ways to solve a coding problem, and requires that you break down a complex problem into subproblems.
Aside from recursion, you should practice using other algorithmic techniques like greediness, divide-and-conquer, backtracking, sliding window, and iteration. In some cases, the most important step in your problem-solving could be deciding on an algorithmic technique.
Google coding interview example questions: recursion
- Solve the "Generate All Possible Balanced Parentheses" problem recursively. (Solution)
- Reverse a linked list (Solution)
- A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). Find all strobogrammatic numbers that are of length = n. (Solution)
- Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass through the root. The length of path between two nodes is represented by the number of edges between them. (Solution)
- Given the
root
node of a binary search tree, return the sum of values of all nodes with value betweenL
andR
(inclusive). The binary search tree is guaranteed to have unique values. (Solution)
2.5 Math↑
Google asks basic discrete math and math problems in a coding context from time to time. So if you’re not confident with your math, you may want to refresh your memory.
Let’s take a look at some example questions.
Google coding interview example questions: math
- Evaluate reverse polish notation and return result (Solution)
- How to connect nodes that randomly appear (Solution)
- A group of two or more people wants to meet and minimize the total travel distance. You are given a 2D grid of values 0 or 1, where each 1 marks the home of someone in the group. The distance is calculated using Manhattan Distance, where distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|. (Solution)
- You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. (Solution)
3. How to answer Google coding interview questions↑
In this section, we’ll give you an answer framework for Google coding interviews and an example answer using the framework.
We’ll also give you a rundown of what we think differentiates a good vs. great Google candidate during coding interviews.
Let’s begin.
3.1 Google coding interview framework↑
To learn how to answer Google coding interview questions, you must first be able to approach them systematically.
You might solve a coding question in different ways, but at the end of the day, you need an approach that will consistently:
- Show your interviewer that you have the knowledge they need
- Break the problem down into manageable steps
Here’s a step-by-step approach that we highly recommend:
- Clarify
- Plan
- Implement
- Test & optimize
Below we’ll go into each step in detail. Let’s get started.
3.1.1 Clarify
Don’t jump straight into the question without consulting your interviewer. Instead, start by asking questions to remove any ambiguity and to explore the edges of the problem.
This is a good time to set up a dialogue with your interviewer. They are not just looking for a candidate who can solve a problem, but one who can work effectively in a team of other engineers.
Let’s jump into how this will look during the interview.
Understand the question
If the question has been written down for you, take the time to read it thoroughly at least twice, to be sure that you’ve picked up on all the details.
Repeat the question back to the interviewer in your own words, so that they can flag anything that you may have initially misunderstood.
Ask clarifying questions
Once you’re sure that you understand the basic question, clarify the unwritten details. For example, ask for constraints (e.g. 0<= N < 1000), consider edge cases, identify corner cases, specify what language you’ll be coding in, etc.
Specify assumptions
Finally, before starting work on the solution, consider any assumptions you’re making (e.g. input format, range, sorted or unsorted list, etc). Specify those to the interviewer, so that they can tell you if that is a correct assumption to make, given the problem.
3.1.2 Plan
Now that you have a complete understanding of the coding question, it’s time to start making your plan. Here is where you can discuss potential approaches with the interviewer, pick the one that is the most appropriate, and lay out the high-level steps to get there.
Let’s take a look at how this will play out in the interview:
Find a solution
Take a few minutes to think through a solution to the problem. It does not need to be optimal at this stage. Map out your solution on the whiteboard or its virtual equivalent, making sure that what you add is comprehensible to both you and the interviewer.
The goal is to find any solution (at least brute-force) and then find improvements. Keep walking through your steps out loud so that the interviewer can guide you.
Explain your solution
Before you implement your plan, make sure that you’ve brought your interviewer up to speed. If you’ve identified multiple approaches to the problem, go over each and explain why you’ve chosen the one you decide to move forward with.
Ensure that the interviewer is aligned with your solution before you start coding. This will help you save time down the road and allow your interviewer to capture the right data points during your coding.
3.1.3 Implement
Now it’s time for the main event. Write legible, clean code rather than pseudocode, and comment out loud on what you’re doing.
Alternatively, if you have a hard time talking and writing, you can spend a few minutes coding quietly, then stop periodically to explain what you’ve done.
Optimize the solution
Once you’ve talked through your solution with the interviewer, optimize it. Consider any points you may have missed when you first thought of the solution, and what you can do to make it better.
Explain your reasoning thoroughly and keep an eye out for the cues of the interviewer, which will let you know whether or not you’re on the right track. You can prompt them by asking, “how does that sound?” before moving on to coding.
Write the code
Now, write that code! Explain what you’re doing, and make an effort to write clearly—don’t use shorthand variables. Include descriptive variable names, structure the code well, consider boundary conditions or empty inputs, etc.
Make your code modular and eliminate duplicate code. If you realize you’ve forgotten an important function, simply go back and insert it, while clarifying what you’re doing out loud.
3.1.4 Test and optimize
Once you have your code on the board, you’ve got to take the time to run through and test it, then optimize it given what you’ve found in testing. Start by testing with a simple example, then try breaking your code with edge and corner cases.
Don’t forget to calculate the time and space complexity of your code, and discuss how you can possibly improve it. If you find any better solutions while testing and evaluating your code’s complexity, ask the interviewer if they’d like you to implement it.
Here’s how that will play out:
Test run your code
When testing your code, run it through multiple cases, starting with the basic use case, moving into a more complex case, and finally test for failure and edge cases.
Consider anything that might break your code, and what you can do to address it [e.g. test cases like assertEquals(findMax(10,20), 20)].
Optimize your code
Finally, work out the time and space complexity of your code. Explain it in simple terms to your interviewer, and use it as a jump-off point to consider ways you can optimize your code.
If time permits, write out the optimal code and discuss it.
Q & A
These last few minutes of the interview are a good time to ask any questions you might have about the company and what your experience would be like working there.
The interviewer may have additional questions for you as well. If the interviewer has clearly moved on from the coding problem, consider it finished and do not try to rehash any of its finer points.
3.2 Example Google coding interview answer↑
To illustrate the framework discussed above, let’s look at a mock coding interview Google posted on its YouTube channel. It shows a high-quality answer to a typical Google coding question.
Below, we’ve provided a transcription of the mock interview for your reference.
To review: first, take a look at the question, and think about how you would approach it. Then carefully watch and read the transcript below and see where their approach differs from yours.
Google mock coding interview example
Question:
A farmer wants to farm their land with the maximum area where good land is present. The land is represented as a matrix with ones and zeroes, where ones mean good land and zeros mean bad land. The farmer only wants to farm in a square of good land with the maximum area. Please help the farmer to find a maximum area of the land they can farm in good land.
Step 1: Clarify
Understand the question
Candidate: May I take a moment to read it and then ask a few clarifications?
Interviewer: Of course.
Candidate: Thank you.
Ask clarifying questions
Candidate: So my first question: must it be a square? The area they want to farm, or could it be a rectangle?
Interviewer: For this problem? We only want it to be returning a square.
Candidate: Awesome. Okay, thank you.
Specify assumptions
Candidate: I can think of like, the naive solution, but probably I shouldn't do this, but I'll just run it by you. I can loop over every position. And for every position, I can basically start from that moment onwards, go left and right, and count however many ones I can find in like a rectangle, or a square, sorry. But that would be if, if let's say the dimensions of the square is like n by n, that would be at best n to the four, which is not ideal. And I assume by posing this question, you want me to find an efficient solution.
Interviewer: Yes.
Step 2: Plan
Find a solution
Interviewer: I'm wondering if you can just visualize what maybe this brute force approach would look like. Maybe using the example.
Explain your solution
Candidate: Sure. Okay, so the brute force if I want to visualize it, so I just pasted the example:
Candidate: ...and I'm going to go over every index, [i] [j] index. And how to— the first, this is the second, this is the third, etc. Let's say we get here in this iteration. So [I] is becoming, let's say two, and [j] is becoming one. In this position, the row and column. So from this point, as every point that we go to, we start another double for loop, going to the right and bottom. So here I go one step to the right. There is a one, so I continue. And then I go to the bottom, there is a one and I continue. And then I go to the right of it, there’s a one, I continue. I wonder if that makes sense. So first we start saying, okay, when we get to this point, we have, you know, that we can do a one by one. Then we ask, can we do a two by two? And if the answer— to answer that, we have to complete the two by two triangle. So we have to look in this vicinity so to speak.
Interviewer: Yes.
Candidate: Then we say okay now yes, I know I can do a two by two starting from this position. Can we— can I do a three by three? And to answer that we have to go on this like, wrapper. Like I'm going to select them one by one because it’s harsh otherwise. So we extend the boundary by one comma, and one row to check that they're all ones there. And then we keep track of the maximum. So if we arrived at three here, then I memorized the three is the best so far, and then until I loop over all the indices possible, maybe I'll update my three to something else and then I’ll return whatever number has been kept. But as we already said, this is not optimal, but it will do the job.
Interviewer: I think that even though this may be a brute force solution, it would be the right approach in checking the nearby values and having that inform how large the square could be.
Candidate: Awesome. And I guess, do you want me to program this brute force solution, or am I'm going to be penalized and should I just think about something better?
Step 3: Implement
Interviewer: We can just move on to maybe what you would consider a more optimal solution.
Candidate: Sure. Awesome. Okay, so these kinds of problems, I feel like I can solve them in two other different ways. The first one would be recursive. So here the recursion can say, let's ignore the zeros because as soon as I find a zero, we can just return. From this point, you can't have a square. But let's say we get to this point it’s like, “oh yes, there's a one so I can make a one by one.” Then we can ask, the surroundings, can we make more than one by one? And then, if I can ask the square next to me… Actually, let me think about it, okay. If this is a one, the right of it is a one. The bottom of it is a one. We can ask this— that I'm highlighting: how big of a square can you make it? Actually...
Interviewer: No, I think you're on the right track, that you're checking the right, below, and diagonal values. But because there is a zero here, does that mean it could be a valid square?
Candidate: Zero is invalid, right?
Interviewer: Yes, yes. That— that would be the case. So based on that, what can you infer that...if you're at that one position at the—that index, yeah.
Candidate: If I'm at the index...
Interviewer: What can you infer is the maximum square?
Candidate: At this index, it’s— it is a one because we can see the diagonal is already a zero.
Interviewer: Yes, yes that's correct. But you then know that the neighboring values are also ones, so there is a possibility that those could have valid squares that are greater than one.
Candidate: Correct. Yes. I mean, in this specific case, because the diagonal is zero, that means this next to this one below it is a zero. Unless we're coming from above.
Interviewer: That’s true. I guess the one below it. Actually neither of those, but you could potentially have, as you're saying, a recursive algorithm. How would that look then?
Candidate: So the recursive algorithm— I'm trying to think out loud as I'm describing the solution. So, basically when we see a one here, we can ask, can this be part of a bigger rectangle? And recursively, how would that look like? We have to ask the neighbors how much—how many ones they have consecutively, contiguously.
Interviewer: Hmmm
Candidate: So that could be saying that, okay, there's a one here, then we can invoke a recursive call that says how many ones are starting at the right of me making a square? So if— I wish I can highlight, but let's imagine me — I'm going to bold this.
Candidate: That marks the end and the beginning of a square. So when I'm at this one right here, I asked the square right of me, “How big of a square can you be?” And—if let's say this whole area had ones, even though it doesn't, if it had all ones, the right of me should say, “Oh, I can do a three by three.” And I'm going to try to break this down into maybe one step at a time. So when I ask this one, “How many ones do you have?” “How big of a square can you form?” It could ask the one right of it, “How many can you form?” It can ask the bottom of it, “How many can you form?”
Interviewer: Yes.
Candidate: And then, if— how—whichever— so, whichever returns the minimum, I will take that and I'll add one to it. Trying to think of this will always be correct. So if this one said, “I can do a two by two.” let's say it claims it can do a two by two. I'm going to change your input by a little bit, if that's okay. So which means this would have been one, this would have been a one.
Interviewer: Okay.
Candidate: And this— the one that I'm highlighting...
Interviewer: I see. So you would compute it like, top down. So that one that you've highlighted, in the— in two two index or two two coordinates would have it contain a three value because it can form that three by three square.
Candidate: Right, exactly.
Interviewer: Got it. Yes, that makes sense.
Candidate: And... let me see if taking the minimum is sufficient, so to speak. So this one can create a three by three, yes. The one right of it can create a two by two —or I guess now the example is so corrupted because I kept changing things. Let's see, actually, this one. Yes. So this one that— maybe I should color. So let me color this to red.
Candidate: The red one will say, “I can do a two by two.” Starting from this coordinate. The blue one will say “I can do a three by three starting at this coordinate.”
Interviewer: Yep.
Candidate: Now, how much can this one create, the one I'm highlighting? It would still be the minimum.
Interviewer: Yes.
Candidate: I’m thinking. Right. Because you can do more than three by three. Okay. So, now we can think about the base cases of the recursion, so to speak.
Interviewer: Yes.
Candidate: So the base case—if we had a zero, then we can do— we return a zero.
Interviewer: Yes.
Candidate: If we had a one, then we ask the right and the bottom to do the recursion. We invoke them.
Interviewer: Yeah.
Candidate: And we return their minimum.
Interviewer: Yes.
Candidate: I'm trying to think, at which case do we—in which case do we grow? I’m thinking we can grow...Let me think. So if this— if the red one, hypothetically said, “I could do a three by three.” I'm just thinking. And the bottom one can say, “I can do a three by three.” I need to think that—there has to be a way that we can grow the one. You know, we have to return a five or something eventually. So if the right of me can say, “I can do a three by three,” which, you know, so maybe I can hack the numbers again, just for the sake of example...
Candidate: ... it can say, “I can do a three by three.” Actually, this is a still a two by two. Okay. I have to do this as a one.
Candidate: So the red one can now do a three by three. The blue one can also do...
Interviewer: Three by three.
Candidate: Only three by three. Exactly. Then this one, is so far is going to say, “Three is the number.”
Interviewer: Yes.
Candidate: However, if this was a one right here.
Interviewer: It would be four.
Candidate: Then it will be four. But let me just, like—
Interviewer: So that would mean the diagonal number would also be three. To which case, because you have a one in that first field, the— at the zero one coordinates. What could that say? If all of the three values down, diagonal, and to your right are all three and this is a one, what could that be?
Candidate: Makes sense. Okay, so if all the values are three, then I should say, “I can do four.”
Interviewer: Exactly. Yeah.
Candidate: Makes sense, okay, okay. So I think— I think I'm able to write it recursively. Of course, the recursion is not the most optimal because it has to retry something multiple times.
Interviewer: Yes.
Candidate: We can always add a memoization memory element to it, this way, each unique invocation will only happens only once.
Interviewer: Yeah.
Candidate: Which will make this be at most, quadratic. We— will invoke at most, n square times. But usually for anything that you can do with memoization, there ought to be a dynamic programming solution where you can do bottoms up. You want me to program the recursive memorization lazy version? Or should I strive for the most efficient dynamic programming version?
Interviewer: I'm thinking that I want to first see your thinking for the bottom up, the dynamic programing solution, and then we can go ahead and code it. I just want to see what you're thinking would be for how bottom up would look.
Candidate: Sure. Okay. You kind of gave me a hint already by saying, “check the diagonal, if it also can do a three by three.” So in that regard, maybe I can have... this is the input we're highlighting right now.
Candidate: We can start with the dynamic programming array that has the same exact size...
Interviewer: Yes.
Candidate: But it's initialized to zero everywhere...
Interviewer: Yep.
Candidate: Then at any moment that I want to compute an entry, I want to populate an entry in this DP matrix that starts with all zeros, I'll be looking at the...the same position of the input, and also the surrounding positions of the input and potentially the surrounding positions of the dynamic programing array, and populated incrementally as such.
Interviewer: And so your DP array would contain which values exactly?
Candidate: So at every entry in the input, if the entry in the input is zero, then we should write zero in the dynamic programming array. If the entry is one, then we need to basically look at the surrounding positions, as you said, like the top position. Just top of me, just left of me, just diagonal left of me, in the dynamic programing array, and we should take the minimum. But if they all agree to be the same value, I'll just increment by one in the DP array. And the final return of this whole program is the maximum entry in the DP array.
Interviewer: Yes.
Candidate: Does that sound correct?
Interviewer: That sounds correct. I do want to highlight that you will be then capturing the height of the square instead of the area in this array. That's fine too, if that's the direction you want to go in.
Candidate: Capturing the height, okay.
Interviewer: Because it is a square, so...
Candidate: It is a square, I see. That’s right, yes.
Write the solution
Candidate: So should I start programming the dynamic solution? And I can explain it as I program it, if that's okay.
Interviewer: That sounds great. Let’s do it.
Candidate: Okay, so programming Python into a document. So maybe I can choose Consolas as a font, and I can say def largest square. And it takes input as a bin_array. Is that fine? Do you want it to be typed or not typed? As in like the typing of Python?
def largest_square(bin_array)
Candidate: Should I do something like this?
def largest_square(bin_array: np.ndarray)->
Candidate: Or at least say it’s a list of list of int?
def largest_square(bin_array: list[list[int]]) ->
Interviewer: Yes, it will be a 2D array of ints, yeah. That’s perfect.
Candidate: Okay. Awesome. So...the answer is just an int, which is the maximum area.
def largest_square(bin_array: list[list[int]]) -> int:
Interviewer: Exactly.
Candidate: Okay. So first I'm going to say my DP array is equal to an error of all zeros. I guess I can— I want to capture first n, which is the length of the bin array, so it could be a five by five, ten by ten, square, etc. It's n by n. So we want to make an all zero. I'm going to do this.
def largest_square(bin_array: list[list[int]]) -> int: n = len(bin_array) dp = [[n]*0 for i in range(n)]
Candidate: Okay so now after this line, DP is just an n by n array with all zeros.
Interviewer: Oh, something that I wanted to point out here is that it's possible that it's m by n. The width and the height do not—
Candidate: May not agree.
Interviewer: Uh yes. For the input array.
Candidate: Good to know.
Interviewer: But your output area should be a square.
Candidate: Thank you for this clarification. Okay, so then I will do this as my n times m.def largest_square(bin_array: list[list[int]]) -> int: n = len(bin_array) m = len(bin_array[0]) dp = [[n]*0 for i in range(m)]
Candidate: So let me just make sure...Yes, I'm consistent in my indexing so to speak, that if an index [i] [j] exists in DP, then it must also exist in bin_array.
Interviewer: Yep.
Candidate: Awesome. Okay, so my DP starts with all zero. Now we're going to do the double for loop that we mentioned. So for I in range(n)...for J in range(m)...and here at every square, we're going to write the maximum that we can do.
Interviewer: Yes.
def largest_square(bin_array: list[list[int]]) -> int: n = len(bin_array) m = len(bin_array[0]) dp = [[n]*0 for i in range(m)] for i in range(n): for j in range(m):
Candidate: So let me think...First, if the entry had the zero, Bin_array of [I] [j] is zero, then in the DP, we’ll have a zero in it.
Interviewer: Yes
Candidate: So in that case, I will just, because the DP was initialized at zero, I can just continue. I can skip to the next iteration. If I’m allowed to use continue.
Interviewer: Yeah, of course.
Candidate: Awesome, okay.
def largest_square(bin_array: list[list[int]]) -> int: n = len(bin_array) m = len(bin_array[0]) dp = [[n]*0 for i in range(m)] for i in range(n): for j in range(m): if(bin_array)[i][j]==0: continue
Candidate: So then at any entry that's not a zero, we should look up the left, and the top, and the diagonal, and we'll see their values. So, maybe I can say, left value is equal to right value. For now. I'll set them later. To the diagonal value all to zero. And I'll set them conditionally. Why? Because I don't want to skip the boundary conditions. So if the left of me, if [I] Yep. And I want to do the same thing, similar thing, to the right one. Otherwise, they will stay at zero.
def largest_square(bin_array: list[list[int]]) -> int: n = len(bin_array) m = len(bin_array[0]) dp = [[n]*0 for i in range(m)] for i in range(n): for j in range(m): if(bin_array)[i][j]==0: continue left = right = diag = 0 if i > 0: left = dp[i-1][j] if j > 0: right = dp[i-1][j]
Interviewer: Quick question: Is it possible to handle the boundaries before you enter this scope?
Candidate: Yes. Yes, I'm sure. So we could copy the boundaries from the input to verbatim. To the DP. And then our loop could be starting from one set from zeros.
Interviewer: I'm thinking more so that if you are in the zeroth index of the row or the column, if there is a handling you could do before you enter this scope of setting the left and right diagonal indices.
Candidate: So you're saying, like, before we enter these loops, we should handle the borders. Maybe that's what I'm hearing.
Interviewer: Maybe, yeah. I think it's possible to do it within the loop, if you'd like.
Candidate: We could.
Interviewer: Or let me know if that doesn't sound right.
Candidate: We could do it. So you are saying that perhaps instead of having these if statements inside the for loop, I could do something before then, I no longer need these if statements.
Interviewer: You could do it outside of the for loop, you could do within the for loop. Either way.
Candidate: I see. Okay, so yes, I could do that. I mean there are many ways to do it. So, I want to think that, yes, okay. So how about, I wonder if it will complain? Okay, so mathematically speaking, I can do this left—Let me know what you think about this. So what if I set it to that and then I just multiply by a Boolean expression? [I] is greater than zero. So here, what I'm trying to do is to say, the I greater than zero, this boolean condition, will only be valid, will only say one, if I'm not at the boundary. If I'm at the boundary, then I can say your left a zero. Is that okay—?
def largest_square(bin_array: list[list[int]]) -> int: n = len(bin_array) m = len(bin_array[0]) dp = [[n]*0 for i in range(m)] for i in range(n): for j in range(m): if(bin_array)[i][j]==0: continue left = right = diag = 0 left = dp[i-1][j]*int(i > 0) if i > 0: left = dp[i-1][j] if j > 0: right = dp[i-1][j]
Interviewer: Yeah, that's possible.
Candidate: That’s possible.
Interviewer: But then if the value is one? Then the maximum square could still be one, even in the row and column, like the edges.
Candidate: Right, so yes, like this right and left and diag, so far, they're just for reading. I still haven't inserted anything into the DP.
Interviewer: Okay
Candidate: My plan is to insert in a moment, like, perhaps right now. Awesome.
Interviewer: Okay
Candidate: Okay, so if [I] is greater than zero and [j] is greater than zero, and now I can read my diagonal. Diag is equal to— I'm going to copy the line for, I’ll just add a minus one. And now I want to write the DP at this moment right here.
left = right = diag = 0 left = dp[i-1][j]*int(i > 0) if i > 0: left = dp[i-1][j] if j > 0: right = dp[i-1][j] if (i > 0 and j > 0): diag = dp[i-1][j-1]
Candidate: So we, just like, we’re brainstorming if they're all— if they’re all set, then I'll read the minimum of the three and increment by one. If they're not all set, then I'll just read the minimum.
Interviewer: Yes. And what would be the deciding factor for that?
Candidate: So to increment by one?
Interviewer: Yes.
Candidate: Basically, the array entry should have a non-zero
Interviewer: Got it.
Candidate: We’re anchored by one. And that's the first if statement in the nested for loop that if we are at zero then we just skip that entry, we keep it in the DP as zero.
Interviewer: Okay
Candidate: So if the code flows until this point, then here I know that it's at a non-zero point, and the top, the left, and the diagonal have some numbers. And using those numbers, the top left or right, some of them could be zeros. The top left diagonal. Some of them could be zeros. If they are all set, that means I should take the minimum plus one.
Interviewer: Okay, that makes sense.
Candidate: Awesome. If left is greater than zero, and right is greater than zero, and diag is greater than zero, then I will set the entry right here. DP[i][j] to the minimum of those. Left right, I think I should put in an array, syntax-wise? I forgot, but I can try that. Plus one. Okay. Let me think.
left = right = diag = 0 left = dp[i-1][j]*int(i > 0) if i > 0: left = dp[i-1][j] if j > 0: right = dp[i-1][j] if (i > 0 and j > 0): diag = dp[i-1][j-1] if (left > 0) and (right > 0) and (diag > 0): dp [i][j] = min ([left, right, diag]) + 1
Interviewer: Quick question. Is there a reason why we need to check that all the values are greater than zero if we are taking the minimum here? If we've already checked that it's not a zero value, do we need to actually check that?
Candidate: We don't need to. You are correct. Yes. So this statement is irrelevant because if any of them is zero, then the minimum will also be a zero, and the final answer will be a one, which is exactly what we need. You’re right, this segment (if (left > 0) and (right > 0) and (diag > 0):) is not needed. If anything, it might make a bug.
Interviewer: That’s perfect.
Candidate: Awesome. So we still don't have the final answer. The final answer is keeping track of what was the maximum. Of course, I can stay within the same computational complexity, and I can just say, return the max over all of this. So return, I guess I'm going to say, rowwise_max is equal to max(row) for row in DP. And then I can return the max of rowwise_max. So rowwise_max in this line, basically it becomes an n numbers. Each number is the maximum in that row, and they return the maximum of those. So we're invoking the max function once in this for loop, and once again on the— list. The final list.
def largest_square(bin_array: list[list[int]]) -> int: n = len(bin_array) m = len(bin_array[0]) dp = [[n]*0 for i in range(m)] for i in range(n): for j in range(m): if(bin_array)[i][j]==0: continue left = right = diag = 0 if i > 0: left = dp[i-1][j] if j > 0: right = dp[i-1][j] if (i > 0 and j > 0): diag = dp[i-1][j-1] dp [i][j] = min ([left, right, diag]) + 1 rowwise_max = [max(row) for row in dp] return max (rowwise_max)
Step 4: Test and optimize
Interviewer: Is there a way to potentially get the maximum or track the maximum within your for loop?
Candidate: Yes, there is a way. I can do that, awesome. Thank you. So I can start as the max_num = -1. And here, every time I update, I basically read off the max. So I can say max_num = max(max_num, dp[i][j]) and then return that at the end.
def largest_square(bin_array: list[list[int]]) -> int: n = len(bin_array) m = len(bin_array[0]) dp = [[n]*0 for i in range(m)] max_num = -1 for i in range(n): for j in range(m): if(bin_array)[i][j]==0: continue left = right = diag = 0 if i > 0: left = dp[i-1][j] if j > 0: right = dp[i-1][j] if (i > 0 and j > 0): diag = dp[i-1][j-1] dp [i][j] = min ([left, right, diag]) + 1 max_num = max(max_num, dp[i][j]) return max_num
Candidate: And of course, if there is some, you know, with every code, there are ways to optimize it. Like for example, specifically here we are storing in an index of an array. We're reading again the same index. I could have stored this as a variable z or temporary variable. But I'm hoping the compiler will take care of that for me. Will make it optimal.
Interviewer: Definitely. This solution looks good to me.
Candidate: Thank you.
3.3 Good vs great Google candidate↑
In order to make the cut when interviewing at Google, you have to distinguish yourself from other candidates. Giving a good answer won’t be enough to get an offer. You’ll need to give a great answer if you want to make an impact.
So here are some details that make the difference between an interview that is just ok, and one that will impress your interviewer:
A “good” or "just ok" Google candidate:
- Completely answers the coding questions, but doesn’t interact with the interviewer
- Interacts with their interviewer, but struggles to take hints or change direction when prompted to do so
- Is able to finish the coding problem, but stumbles through their behavioral questions at the start of the interview
- Gets stuck once or twice during the interview and struggles quietly until they are able to move past it
- Offers a complete solution that is difficult to follow
- Comes up with a workable solution after coming to quick conclusions that they haven't verified with the interviewer
- Follows one approach that works, but neglects to examine its tradeoffs or other possible approaches
- Tests the code after being prompted by the interviewer to do so
- Finishes and tests the code by the end of the session, but does not leave time to consider space and time complexity
A “great” Google candidate:
- Is able to change direction and dive deeper on specific aspects when asked
- Has prepared responses to common behavioral questions and can transition smoothly into the coding portion
- Is able to talk through the problem when they get stuck, attack it from multiple angles, and take hints from their interviewer
- Points out the common pitfalls of the programming language they’ve chosen
- Offers a complete solution that is easy to follow, with clearly defined variables and space for corrections
- Considers multiple approaches to the problem and clearly explains why the one they choose is the most efficient
- Works steadily and methodically, only coming to conclusions after having thought and worked through certain aspects
- Proactively tests the code and identifies bugs before the interviewer points them out
- Examines the space and time complexity of the code, offering to optimize certain aspects where applicable
Ultimately, being a great candidate boils down to having the right mix of technical knowledge and communication skills to both work out the problem and dialogue with the interviewer. For extra tips on coding interviews, take a look at our list of 21 coding tips from ex-interviewers.
So you’ll need to prepare for your interview by brushing up on technical concepts and soft skills like communication. We’ve got a preparation plan to help you do that in our next section.
4. How to prepare for Google coding interview questions↑
As you can see from the information above, there is a lot of ground to cover when it comes to your Google coding interview preparation. So, it’s best to take a systematic approach to make the most of your practice time. We recommend the three steps below.
4.1 Practice on your own
Before you start practicing interviews, you’ll want to make sure you have a strong understanding of the relevant algorithms and data structures. Once you’re confident in all of these, practice your skills by working through lots of coding problems.
Here are some resources from Google:
We also recommend using the coding guides we’ve linked in this article, as well as our article on how to get better at coding interviews (with tips from FAANG interviewers).
If you want to skip straight to solving questions, our ultimate data structure interview questions list is a great place to start. Many candidates on Glassdoor also recommend looking for Google-tagged Leetcode problems (in the medium and difficult levels) to practice with.
One of the main challenges of coding interviews is that you have to communicate what you are doing as you are doing it. Having to think, code, and communicate your thoughts to the interviewer all at the same time is not easy.
With that in mind, don't let the first interview you do be the real thing. Instead, we highly recommend getting some mock interviews under your belt.
4.2 Practice with peers
If you have friends or peers who can do coding mock interviews with you, that's an option worth trying. It’s free, but be warned, you may come up against the following problems:
- It’s hard to know if the feedback you get is accurate
- They’re unlikely to have insider knowledge of interviews at your target company
- On peer platforms, people often waste your time by not showing up
For those reasons, many candidates skip peer mock interviews and go straight to mock interviews with an expert.
4.3 Practice with experienced coding interviewers
In our experience, practicing real coding interviews with experts who can give you company-specific feedback makes a huge difference.
Find a Google coding interview coach so you can:
- Test yourself under real interview conditions
- Get accurate feedback from a real expert
- Build your confidence
- Get company-specific insights
- Save time by focusing your preparation
Landing a job at a big tech company often results in a $50,000 per year or more increase in total compensation. In our experience, three or four coaching sessions worth ~$500 make a significant difference in your ability to land the job. That’s an ROI of 100x!