Manual List Operations

Lesson Overview

Welcome to this lesson focused on manual List Operations. Building on the manual traversal techniques introduced earlier, this lesson dives into specific patterns you will encounter frequently: counting occurrences, finding the index of a value, and reversing a list. Applying these patterns in isolation will sharpen your ability to solve more complex problems and prepare you for scenarios where built-in functions are unavailable or need to be replicated with custom logic.

Quick Introduction

With loops and indices already in your toolkit, the focus here shifts to recognizing when and how to apply them for search, frequency, and reversal tasks. Each pattern follows a clear structure: initialize a result variable, iterate through the list, and update the result based on a condition. Internalizing these structures will let you adapt them quickly under pressure.

Manual Implementation Examples

To perform these operations, we typically use for loops and access elements via their index. Here is how you can implement these common tasks manually:

Counting Occurrences

To count how many times a specific value appears, iterate through the list and increment a counter whenever a match is found.

val items = listOf(10, 20, 30, 20, 40, 20)
val target = 20
var count = 0

for (item in items) {
    if (item == target) {
        count++
    }
}
// count is 3

Finding the Index

To find where an element is located, iterate through the indices of the list. When the element at the current index matches the target, you have found the position.

val colors = listOf("red", "green", "blue", "yellow")
val targetColor = "blue"
var foundIndex = -1

for (i in 0 until colors.size) {
    if (colors[i] == targetColor) {
        foundIndex = i
        break // Stop searching once found
    }
}
// foundIndex is 2

Reversing a List

Following the logic used in string manipulation, you can reverse a list by iterating through it backward using a decreasing range.

val original = listOf(1, 2, 3, 4, 5)
val reversed = mutableListOf<Int>()

// Start from the last index down to 0
for (i in original.size - 1 downTo 0) {
    reversed.add(original[i])
}
// reversed contains [5, 4, 3, 2, 1]

Getting Started with Practice!

Grasping the concepts covered in this lesson is critical to succeeding in the practice exercises that follow, so take the time to understand these concepts thoroughly. Remember, we are not just learning algorithms but cultivating a deeper understanding of how we can break down and solve complex problems with relatively simple code. Therefore, get ready and anticipate an exciting, revealing practice session!

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal