Post

Length, Size and Count in Kotlin

Length, Size and Count in Kotlin

A quick reference guide for length and size operations you’ll frequently need in competitive programming and problem-solving.

Quick Reference Table

Data StructureProperty/FunctionReturnsExampleNotes
StringlengthInt"kotlin".lengthProperty, not function
ArraysizeIntarrayOf(1,2,3).sizeProperty
List/SetsizeIntlistOf(1,2,3).sizeProperty
MapsizeIntmapOf("a" to 1).sizeCount of key-value pairs
CollectionisEmpty()Booleanlist.isEmpty()Preferred over size == 0
CollectionisNotEmpty()Booleanlist.isNotEmpty()Preferred over size > 0
IntRangecount()Int(1..10).count()Size of range

Common Problem-Solving Patterns

String Operations

1
2
3
4
5
6
7
8
val str = "kotlin"
str.length                  // 6
str.lastIndex              // 5 (length - 1, useful in loops)
str.indices               // 0..5 (range of valid indices)

// Check if empty
str.isEmpty()             // false
str.isBlank()            // false (empty or only whitespace)

Array Operations

1
2
3
4
5
6
7
8
9
val arr = arrayOf(1, 2, 3)
arr.size                  // 3
arr.indices              // 0..2
arr.lastIndex            // 2

// 2D Array
val matrix = Array(3) { IntArray(4) }
matrix.size              // 3 (rows)
matrix[0].size          // 4 (columns)

Collection Operations

1
2
3
4
5
6
7
8
9
10
11
val list = listOf(1, 2, 3)
list.size                // 3
list.lastIndex          // 2

// For problem solving
list.first()            // 1 (first element)
list.last()             // 3 (last element)
list.getOrNull(5)       // null (safe access)

// Count elements matching condition
list.count { it > 1 }   // 2 (elements greater than 1)

Map Operations

1
2
3
4
val map = mapOf("a" to 1, "b" to 2)
map.size                // 2
map.keys.size          // 2 (number of keys)
map.values.size        // 2 (number of values)

Performance Tips

  • Use isEmpty() instead of size == 0 (more idiomatic and sometimes more efficient)
  • lastIndex is better than size - 1 for readability
  • For large collections, count() with predicate traverses the entire collection, use with care

Common Pitfalls to Avoid

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// ❌ Don't do this
if (list.size == 0)   
if (str.length == 0)  

// ✅ Do this instead
if (list.isEmpty())   
if (str.isEmpty())    

// ❌ Don't do this in loops
for (i in 0..list.size)      // Includes size, causes IndexOutOfBounds
for (i in 0..list.size-1)    // Works but not idiomatic

// ✅ Do this instead
for (i in list.indices)      // Range of valid indices
for (i in 0 until list.size) // Excludes size

Remember: In Kotlin, prefer properties (size, length) over function calls when available, and use built-in ranges (indices, lastIndex) for cleaner code.

This post is licensed under CC BY 4.0 by the author.