Functional Programming
  • Preface
  • Getting Started
  • Sorting
    • Bubble Sort
    • Merge Sort
    • Insertion Sort
  • Stacks
    • Stack
  • Queues
    • Queue
    • Binary Heap (Priority Queue)
  • Trees
    • Binary Tree (Unbalanced)
    • Prefix Trie
  • Graphs
    • Undirected
    • Directed
    • Edge Weighted
  • Dynamic Programming
    • Knapsack
    • Longest Common Substring
    • Staircase
  • Leetcode/InterviewBit
    • 2 Sum [Easy]
    • Longest Valid Parentheses [Medium-Hard]
    • Kth Smallest Element [Medium]
    • Max Profit [2 variations: 1st Easy 2nd Hard]
    • Pretty Print 2D Matrix [Easy]
    • Max Contiguous Subarray (Kadane's) [Medium (just cause its tricky)]
    • Permutations [Medium]
    • Next Permutation [Medium]
Powered by GitBook
On this page

Was this helpful?

  1. Leetcode/InterviewBit

Kth Smallest Element [Medium]

https://www.interviewbit.com/problems/kth-smallest-element-in-the-array/

Straightforward problem description: Find the kth smallest element in an array. Easiest approach I could think of is to use a queue. Didn't see a more optimal solution on the platform (InterviewBit) that this question popped up on

import scala.collection.mutable.PriorityQueue

def kthsmallest(A: Array[Int], B: Int): Int = {

  @tailrec
  def go(pq: PriorityQueue[Int], i: Int): Int = {
    if (i == A.length) {
      pq.head
    } else {
      go(
        if (pq.length == B) {
          if (A(i) < pq.head) (pq += A(i)).tail
          else pq
        } else {
          pq += A(i)
        },
        i + 1
      )
    }
  }

  val order = new Ordering[Int] {
    override def compare(x: Int, y: Int): Int =
      implicitly[Ordering[Int]].compare(x, y)
  }

  A.lift(0).fold(0)(elem => go(PriorityQueue[Int](elem)(order), 1))

}
PreviousLongest Valid Parentheses [Medium-Hard]NextMax Profit [2 variations: 1st Easy 2nd Hard]

Last updated 6 years ago

Was this helpful?