Sunday, September 2, 2012

Set matrix rows and cols to zero


Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column is set to 0.

Approach:

  1. Iterate through the matrix, and where ever we encounter 0, remember the row and col in separate arrays.
  2. Do the second iteration through the matrix for the rows and cols stored above and mark them zero.


Sample Input/Output:
printing original matrix..
1 2 0 
4 5 6 
0 8 9 
After removing zero rows and cols: 
0 0 0 
0 5 0 
0 0 0 
printing original matrix..
4 5 6 
7 0 8 
9 1 2 
After removing zero rows and cols: 
4 0 6 
0 0 0 
9 0 2 

Replace Spaces

Write a method to replace all spaces in a string with ‘%20’.

Sample Input/Output:


String: this is a nice world!
replaced space with %20: this%20is%20a%20nice%20world!

Is Anagram

Write a method to decide if two strings are anagrams or not.

Sample Input/Output:

first String: tea
second String: eat
Is Anagram: true

first String: teas
second String: seat
Is Anagram: true

first String: peas
second String: peat
Is Anagram: false

Remove Duplicate Characters from String


Design an algorithm and write code to remove the duplicate characters in a string without using any additional buffer.

Sample Input/Output:

String: programming
after removing duplicate chars: progamin
String: words
after removing duplicate chars: words
String: texts
after removing duplicate chars: texs
String: a
after removing duplicate chars: a
String: aa
after removing duplicate chars: a
String: ba
after removing duplicate chars: ba

Unique Characters in a String

Implement an algorithm to determine if a string has all unique characters. What if you can not use additional data structures?

SAMPLE Input/Output:

String: abcb
Has Unique chars: false
String: want
Has Unique chars: true
String: calls
Has Unique chars: false
String: x
Has Unique chars: true
String: 
Has Unique chars: true
String: aa
Has Unique chars: false
String: mn
Has Unique chars: true