Categories
Studio

Kotlin for Interviews — Part 4: Iteration | by Sherry Yuan

Sherry Yuan
Photo courtesy And gold on Release the splash

This is Part 4 of Kotlin for Interviews. This series describes Kotlin’s functions and code snippets that came up frequently while preparing for an Android interview. We also edited a cheat sheet that covers all five parts of this series. Here..

Part 1: You can find common data types Here, Part 2: Collection function Here Part 3: Numbers and Mathematics Here And Part 5: Frequently used code snippets Here..

The contents of this part are as follows:

Many interview questions require some iterations, whether working with input arrays or using maps to store information, so there are different ways to iterate through some common data structures. I will explain.

A Range In Kotlin, it’s a set of values ​​defined by a start value, an end value, and a step. The default value for the step, the distance between two values, is 1. The most frequently encountered are: IntRange, But you can use LongRange And CharRange In the same way.

  • forEach() Performs the specified action on each element in the collection. This is the iterative method I use most often in regular projects, but I didn’t use it much in interviews for reasons 1). forEach() Throw ConcurrentModificationException If you try to modify the collection while iterating through the collection, and 2) many of the interview issues, you also need to consider the index.
  • forEachIndexed() Is like forEach()However, you can also access the index of the element in the lambda. This is often needed for interview issues.
// Print elements at even indices.
list.forEachIndexed { index, element ->
if (index % 2 == 0) println("$element")
}
  • ..,alias rangeTo()Can be used in the form of for(i in a..b) Create and repeat Range.. The range starts (a) And the end (b) Since it is an element, if you want to use it to iterate over a list / array, you need to write: for (i in 0..list.size-1) Or use until instead of.Although it is most often used Ints, can be iteratively processed Chars too.
// Iterate and print from i = 0 to i = 100
for (i in 0..100) { println(i) }
// Iterate from i = 0 to i = list.size-1
for (i in 0..list.size-1) { println(list[i]) }
// Iterate and print 'a', 'b', 'c', 'd'
for (i in 'a'..'d') { println(i) }
  • downTo() Works like ..Except that each iteration goes down one step instead of one.
// Iterate and print from i = 100 to i = 0
for (i in 100 downTo 0) { println(i) }
  • step() You can specify the change in value between each iteration.
// Iterate and print 1, 3, 5, 7
for (i in 1..8 step 2) { println(i) }
// Iterate and print 8, 5, 2
for (i in 8 downTo 1 step 3) { println(i) }
  • until() It contains the start element but not the end element. This is my preferred way to iterate over the index of a collection. If you use the size of the list last, you don’t have to worry about the index going out of range.
// Iterate and print from i = 0 to i = 99
for (i in 0 until 100) { println(i) }
// Iterate and print elements from i = 0 to i = list.size-1
for (i in 0 until list.size) { println(list[i]) }
  • indices Returns IntRange Represents a valid index for a collection and can be used as follows: until()..
val list = listOf('a', 'b', 'c')
println(list.indices)
// Prints 0..2
// Iterate and print elements from i = 0 to i = 2
for (i in list.indices) { println(list[i]) }
  • repeat() Executes the specified function action the specified number of times.
// Print "Hello" 100 times
repeat(100) {
println("Hello")
}

This is rarely seen in real-world projects, but it always happens in interview issues. Grids, mazes, graphs, etc. may all be represented using 2D arrays.

This is my preferred way to iterate over a 2D array or list using. until:

if (grid.isEmpty()) return
for (i in 0 until grid.size) {
for (j in 0 until grid[0].size) {
println(grid[i][j])
}
}

Or indices:

if (grid.isEmpty()) return
for (i in grid.indices) {
for (j in 0 until grid[0].size) {
println(grid[i][j])
}
}

Maps are also common in interview issues, especially as a good way to store information when the list isn’t enough.

If you need to iterate over key / value pairs, you can use one of the following: for Loop or forEach loop. This depends on personal preference.

// Iterate through entries using a for-loop
for ((key, value) in map) {
println("$key = $value")
}
// Iterate through entries using forEach()
map.forEach { (key, value) -> println("$key = $value") }

If you just need to iterate over the keys, keys Val to get Set Iterate over all the keys in the map.

map.keys.forEach { println(it) }

Similarly, if you only need to iterate over the value, values val returns Set Of all the values ​​in the map.

map.values.forEach { println(it) }

PriorityQueueIs useful when you want to process elements based on priority. These are often used in interview questions that require K-th largest, K-th smallest, top K frequency, and more. We’ve covered it in detail in Part 1, but here it reminds us of what the iterations look like.

val pq = PriorityQueue<Int>(listOf(2, 1, 3))
// pq will be empty after 3 iterations
while(pq.isNotEmpty()) {
println(pq.poll())
// prints 1, then 2, then 3
}

That’s it for Part 4.This is Link to cheat sheet Cover all five parts again.

Source

Leave a Reply

Your email address will not be published. Required fields are marked *