Popular Posts

Monday, September 12, 2011

Generate all the strings of n bits

Problem:
Generate all the strings of n bits.
Solution:
Subtract and Conquer.
Complexity: O(2^n)
Code:

Tuesday, August 30, 2011

Problem:
Given an array of integers. How do we pick two numbers such that their sum is closest to zero.
Solution: 

  • Sort the array by comparing absolute value.
  • traverse the array once to find the two consecutive numbers with minimum sum.

Complexity: O(n log n)
Code:



Sunday, August 28, 2011

a1a2a3....anb1b2b3....bn to a1b1a2b2a3b3....anbn

Problem:
Convert a1a2a3....anb1b2b3.....bn to
a1b1a2b2a3b3.....anbn
in O(n) time and O(1) space
Solution:

[b]       a c d e 1 2 3 4 5      [2<=5, index=2*2-1=3]
[c]       a b b d e 1 2 3 4 5      [3<=5, index=3*2-1=5]
[e]       a b b d c 1 2 3 4 5      [5<=5, index=5*2-1=9]
[4]       a b b d c 1 2 3 e 5      [9>5, index=(9-5)*2=8]
[3]       a b b d c 1 2 4 e 5      [8>5, index=(8-5)*2=6]
[1]       a b b d c 3 2 4 e 5      [6>5, index=(6-5)*2=2]
[b]       b d c 3 2 4 e 5      [startindex=index=2]
[d]       a 1 b d c 3 2 4 e 5      [4<=5,index=4*2-1=7]
[2]       a 1 b d c 3 d 4 e 5      [7>5,index=(7-5)*2=4]
[d]       a 1 b c 3 d 4 e 5      [startindex=index=4]

Complexity: O(n) time O(1) space
Code: