Package level functions in ScalaJuly 24, 2014

I was a bit suprised when I first found out that Scala doesn’t directly support defining functions directly in the package scope:

\\ Compilation error: wrong top level declaration
package com.example.hello;

def hello() {
    println("hello")
}

This restriction probably comes from Java, in which all functions must be defined as methods of classes. But it is still a bit weird since Scala claims to support functions as first class values.

Anyway, there are workarounds. To create private package level functions, we can do:

more »

Finding duplicate elements in an arrayOctober 14, 2012

We have an array of length 100, which contains numbers ranging from 0 and 99. There is exactly one duplicate number in this array. Write a program to find out this number.

I was asked this question yesterday during a phone interview. Like almost all phone interview questions, it appears to be simple. But there are actually several interesting O(1) space O(n) time solutions.

more »

Generating all permutations of a stringOctober 01, 2012

Given a string, print all its permutations.

There is an elegant in-place recursive solution for this problem. The idea is, for the first position, select one character from the string. Then select another character for the second position from remaining characters. Continue util we have selected a character for every position.

more »