Designer, Craftsman

Code Samples

Kotlin Code Samples

 1. Two Sum

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

/**
 * Returns indices of two numbers in the array that add up to the target.
 *
 * @param nums   array of integers
 * @param target target sum
 * @return array of two indices
 */
fun twoSum(nums: IntArray, target: Int): IntArray {
    // Create a HashMap to store numbers as keys and their indices as values
    val map = HashMap<Int, Int>()
    
    // Iterate through the array
    for (i in nums.indices) {
        // Calculate the complement of the current number
        val complement = target - nums[i]
        
        // Check if the complement is already in the map
        if (map.containsKey(complement)) {
            // If it is, return the indices of the complement and the current number
            return intArrayOf(map[complement]!!, i)
        }
        
        // If not, add the current number and its index to the map
        map.put(nums[i], i)
    }
    
    // If no solution is found, throw an exception
    throw IllegalArgumentException("No solution found")
}

2. Reverse Linked List

Given the head of a singly linked list, reverse the list and return the reversed list.

Kotlin

/**
 * Node class for a singly linked list.
 */
class ListNode(var `val`: Int) {
    var next: ListNode? = null
}

/**
 * Reverses a singly linked list.
 *
 * @param head head of the list
 * @return reversed list
 */
fun reverseList(head: ListNode?): ListNode? {
    // Initialize previous node to null
    var prev: ListNode? = null
    
    // Initialize current node to head
    var curr = head
    
    // Iterate through the list
    while (curr != null) {
        // Store the next node in a temporary variable
        val nextTemp = curr.next
        
        // Reverse the link of the current node
        curr.next = prev
        
        // Move previous and current nodes one step forward
        prev = curr
        curr = nextTemp
    }
    
    // Return the new head of the reversed list
    return prev
}

3. Maximum Subarray

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Kotlin

/**
 * Returns the maximum sum of a contiguous subarray.
 *
 * @param nums array of integers
 * @return maximum sum
 */
fun maxSubArray(nums: IntArray): Int {
    // Initialize maximum sum so far to the first element
    var maxSoFar = nums[0]
    
    // Initialize maximum sum ending at the current position to the first element
    var maxEndingHere = nums[0]
    
    // Iterate through the array starting from the second element
    for (i in 1 until nums.size) {
        // Update maximum sum ending at the current position
        maxEndingHere = Math.max(nums[i], maxEndingHere + nums[i])
        
        // Update maximum sum so far
        maxSoFar = Math.max(maxSoFar, maxEndingHere)
    }
    
    // Return the maximum sum
    return maxSoFar
}

4. Valid Parentheses

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

Kotlin

/**
 * Returns true if the input string has valid parentheses.
 *
 * @param s input string
 * @return true if valid, false otherwise
 */
fun isValid(s: String): Boolean {
    // Create a stack to store opening parentheses
    val stack = Stack<Char>()
    
    // Iterate through the string
    for (c in s.toCharArray()) {
        // If the character is an opening parenthesis, push it to the stack
        if (c == '(' || c == '{' || c == '[') {
            stack.push(c)
        } else {
            // If the stack is empty, return false
            if (stack.isEmpty()) return false
            
            // Pop the top of the stack
            val top = stack.pop()
            
            // Check if the popped character matches the current closing parenthesis
            if ((c == ')' && top != '(') || (c == '}' && top != '{') || (c == ']' && top != '[')) {
                return false
            }
        }
    }
    
    // If the stack is empty, return true
    return stack.isEmpty()
}

5. Merge Two Sorted Lists

Merge two sorted linked lists and return it as a new sorted list.

Kotlin

/**
 * Merges two sorted linked lists.
 *
 * @param l1 first list
 * @param l2 second list
 * @return merged list
 */
fun mergeTwoLists(l1: ListNode?, l2: ListNode?): ListNode? {
    // If the first list is null, return the second list
    if (l1 == null) return l2
    
    // If the second list is null, return the first list
    if (l2 == null) return l1
    
    // If the value of the first node in the first list is smaller
    if (l1.`val` < l2.`val`) {
        // Recursively merge the rest of the first list with the second list
        l1.next = mergeTwoLists(l1.next, l2)
        return l1
    } else {
        // Recursively merge the first list with the rest of the second list
        l2.next = mergeTwoLists(l1, l2.next)
        return l2
    }
}