Tuesday, June 3, 2014

What I keep in my .bashrc or .profile

As of now:


alias c="cd"
alias d="cd ../"
alias g="grep"
alias l="ls"
alias p="pwd"
alias v="gvim"
alias vv="vim"
alias br="vim ~/.bashrc"
alias cs="cscope -d"
alias ll="ls -l"
alias sc="source ~/.bashrc"
alias sv="source ~/.vimrc"
alias vr="vim ~/.vimrc"


export PS1='\[\033[32m\]\h:\[\033[35m\]\w\[\033[32m\]$\[\033[35m\]'
#COMMENT: color format command [\033[32m user \]\h:\[\033[35m\]\w(workspace directory)\[\033[32m\]$\[\033[35m what we type in\]

.bashrc on MAC OS X (Snow Leopard, Mountain Lion, Mavericks, Yosemite)

Mac OS X does not have .bashrc file, instead there is .profile
To create this(if it already does not exist), create a profile in ~/.profile and treat it like a normal bashrc 
Note that ~ means /Users/MyUserName

Friday, March 28, 2014

Algo question: write "bool isSplitable(int[] arr)" to return true if the arr can be divided into two parts having the equal sums


First lets prove that an array can be split at only one point:

E.g
Array = [……….17……….19]
Lets say its split able at 19. To be also split able at 17, the sum of numbers b/w 19 and 17 would have to be -ve(-2 in this case). Which means sum total going from 17 to 19 would be < 17 (=15 in this case). So array would not be split able at 19.

Same can be proven if there is a num > 19 say 23





Now, for quickest run time, we’ll use an extra array to hold the sums.(S)
Algo would be:
Going forward, add and store the sum till that idx i into S[i].
Once the end is reached, walk backward, adding the sum of terms from back
and compare with the sum from front (S[i]
If match found, return true, else return false

Run time would be O(n)



Code(C++):

#include <iostream>
#include <map>
#include <tr1/unordered_map>
#include <tr1/unordered_set>

using namespace std;
using namespace tr1;


bool isSplittable(int *A, int size){

if(size < 2){return false;}

//array to hold sums
int *S = new int[size];
S[0] = A[0];
int i = 1;
int bkwd_sum = A[size-1]; //to hold sum while walking backwards
int fwd_sum = 0;
//put forward sum into S from 0 to len - 1
//cout << "S[0]" << S[0] << endl;
while(i<size-1){
//cout << "i: " << i << endl;
//cout << "A[i] " << A[i] << endl;

S[i] = S[i-1] + A[i];
//cout << "S[i] " << S[i] << endl;

i++;
}
i--;
//cout << "==============================" << endl;

//Start walking backwards till a match in sum is found
while(i>0){
fwd_sum = S[i];
//cout << "i: "  << i << endl;
//cout << "bkwd_sum: " << bkwd_sum << endl;
//cout << "fwd_sum "<< fwd_sum << endl;

if(fwd_sum == bkwd_sum){
cout << "array can be split at idx:" << i << endl;
return true;
}
bkwd_sum = bkwd_sum + A[i];
i--;
}

return false;
}

int main (int argc, char * const argv[]) {
int a[7] = {5, 7, 10, 10, -30, 17, 19};
int size = sizeof(a)/sizeof(int);

isSplittable(a, size);



return 0;
}

Wednesday, March 26, 2014

Unix/Linux: Device or resource busy, cannot delete

If you ever get a message like ..../dc3/stats_asdf/inc/.nfs00000000022b4f4d0009aa': Device or resource busy
when you try to delete a folder using rm -fr ..


This most probably means that there is a process running on your machine that is currently using this directory.


Solution: Kill the process. Run ps -ef | grep "your username etc." Identify the culprit process and kill it using kill (-9) PID

Using -Werror option

Werror takes warnings as errors and therefore prevents compilation even if there is a warning.

Wednesday, March 19, 2014

Find all permutations of string

Given string s, find all permutations of it. Don't worry about repeating.
E.g.: "hat" should give o/p:
“tha”, “aht”, “tah”, “ath”, “hta”, and “hat"

E.g.  "aaa" should give o/p aaa 6 times

-Note that repetition can be simply avoided by using a hashmap to quickly check if that permutation has been counted or not

C++ prog:

#include <iostream>
#include <map>
#include <vector>
#include <tr1/unordered_map>
#include <tr1/unordered_set>

using namespace std;
using namespace tr1;

void printVec(vector<string> v){
int i = 0;
cout << "start printing vec: "<< endl;
while(i < v.size()){
//cout << "i: " << i << endl;
cout  << v[i] << endl;
i++;
}
cout << "stop printing vec, i: " << i << endl;
return;
}


vector<string> perms(string s){
//cout << "input string: " << s << endl;
string temp;
vector<string> v (0);
if(s.length() <= 0){
//cout << "input string blank: " << s << endl;
temp = "";
v.push_back(temp);
//cout << "return vector: " << endl;
//printVec(v);
return v;
}
char c;
int i = 0; int j = 0;
vector<string> ret_vec (0);
string temp1;

c = s[0];
temp = s.substr(1, (s.length()-1));
ret_vec = perms(temp);

while(i < ret_vec.size()){
temp = ret_vec[i];
//cout << "======================================="<< endl;
//cout << "i: " << i << "  temp: " << temp << endl;
j = 0;

while(j <= temp.size()){
temp1 = temp;
temp1.insert(j, 1, c);
//cout << "j: " << i << "  temp1: " << temp1 << endl;
v.push_back(temp1);
j++;
}
i++;
}
//cout << "final return vector: " << endl;
//printVec(v);
return v;
}


int main (int argc, char * const argv[]) {
string s = "aaa";
vector<string> v (0);
v = perms(s);
printVec(v);
    return 0;
}

Tuesday, March 18, 2014

Algorithm question: Write a function to reverse the order of the words in a string

E.g.:  empty string here    o/p: here string, empty

C++ Prog:

#include <iostream>
#include <map>
#include <tr1/unordered_map>
#include <tr1/unordered_set>

using namespace std;
using namespace tr1;


string reverseWordBtwIdx(string s, int i, int j){
if (i >= j) {return s;}
if (s.length() <= 1){return s;}
char c;

while(i < j){
c = s[i];
s[i] = s[j];
s[j] = c;
i++; j--;
}
return s;
}


void reverseWords(string s){
if (s.size() == 0){
cout << "empty string" << endl;
return;
}
int i = 0; //start idx
int j = s.length() - 1; //end idx
int itr = 0;

cout << "original string: " << s << endl;
s = reverseWordBtwIdx(s, 0, s.length()-1);

i = 0;
while(itr < s.length()){
i = 0; j = 0;

if(s[itr] != ' ')
{
i = itr; j = itr+1;
while(j < s.length()){
if(s[j] == ' '){
break;
}
j++;
}
if (j >= s.length()){
j = s.length();
}
s = reverseWordBtwIdx(s, i, j-1);
itr = j+1;
}
else{itr++;}
}
cout << "final string: " << s << endl;
return;
}


int main (int argc, char * const argv[]) {
string s = "empty string, here";

reverseWords(s);


    return 0;
}

Friday, March 14, 2014

Find inorder successor in BST

A frequently asked question is: Find the next in order successor in a BST.

Algorithm would be:

If (node has a rightChild){
find min in right subtree i.e. go right and keep going left
till you encounter a NULL
}
else if (node is a leftChild of its parent){
parent is the in order successor
}
else{
node is the right Child.
while(parent != NULL){
1. Keep going up the parents till you find a node that is
the left child of its parent. That parent is the in order successor
or 2. Keep going up till you find a node >= current node
}
if no successor found this means that the node was the rightmost
one and has no successor
}

As an example:
Tree:
                      30
          20                       42
    10           27       37             45
 2     15   22               39     44    50

Third case(node is rt child) needs elaboration:
E.g. Say node is 27, keep going up till you find a node >= 27 i.e. 30, this is the ans
E.g. Node is 15, go up till you find a node that is left child, node is 10, its parent i.e 20
        is the required ans
                   













Saturday, March 1, 2014

Interview question: If [a1,a2,a3...,an,b1,b2...bn] is given input change this to [a1,b1,a2,b2.....an,bn] , solution should be in-place

Two solutions:
1. Swap middle pair, and keep swapping increasing number of pairs from the middle:

C++ implementation:
void arrangeArray(int *a){
int num_swaps = 1; //number of swaps to be done
int i = 0;
int mid=0;
int swap_start_idx = 0;
int swap_end_idx = 0;
int temp=0;

//find lenght of array
while(a[i] != '\0'){
i++;
}
mid = i/2 -1;
cout << "mid: " << mid << endl;
i=0;
while(a[i] != '\0'){
cout << a[i] << endl;
i++;
}

while(mid -num_swaps +1 > 0){
swap_start_idx = mid-num_swaps+1;
swap_end_idx = mid+num_swaps;
//cout << "num_swaps: " << num_swaps << " swap_start_idx " << swap_start_idx << "  swap_end_idx "<< swap_end_idx << endl;
while(swap_end_idx > swap_start_idx){
temp=a[swap_start_idx];
a[swap_start_idx]=a[swap_start_idx+1];
a[swap_start_idx+1] = temp;
//cout << "a[swap_start_idx]: " <<  a[swap_start_idx] << "  a[swap_end_idx]: " << a[swap_end_idx] << endl; 
swap_start_idx += 2;
}
num_swaps++;
//cout << "num_swaps" << num_swaps << endl;
}
return;

}


int main () {
    int a[] = {1,3,5,7,2,4,6,8};
int i=0;
while(a[i] != '\0'){
cout << a[i] << endl;
i++;
}
arrangeArray(a);
i=0;
while(a[i] != '\0'){
cout << a[i] << endl;
i++;
}
 return 0;
}

Find all unique substrings of a string

/*
 copyright: Puneet Sohi
 */



#include <iostream>
#include <string>
#include <vector>
#include <tr1/unordered_map>

using namespace std;
using namespace tr1;

vector<string> findSubStr(string s){
//find all unique substr of s. Hashmap used
//to filter out the duplicates
vector<string> v (1);
vector<string> v1 (1);
char c;
int i=0;
string s1, t;
string subS;
unordered_map<string, int>m;
    if(s.length() <= 1){
    c = s[0];
s1.append(1, c);
v[0] = s1;
return v;
}
c = s[0];
s1.append(1,c);
v[0] = s1;
m[s1] = 1;
    subS = s.substr(1, s.length()-1);
v1 = findSubStr(subS);
for(i=0; i < v1.size(); i++){
    t = v1[i];
if(m[t] == 0){
v.push_back(t);
m[t] = 1;
}
t = s1 + t;
if(m[t] == 0){
v.push_back(t);
m[t] = 1;
}
}
return v;
}

int main () {
int i = 0;
string s1 = "aa";
vector<string> v (1);
v = findSubStr(s1);
    while(i<v.size()){
cout << v[i] << endl;
i++;
}
    return 0;
}


Longest Common Substring

The longest common substring problem can be easily solved using a matrix approach.
A simple google search will show the process.

Here is a working C++ code of the same:

/*
 Copyright: Puneet Sohi 
 */


#include <iostream>
#include <string>
#include <vector>
#include <tr1/unordered_map>

using namespace std;
using namespace tr1;

void findLongestCommonSubstring(string s1, string s2){
if (s1.size() == 0 || s2.size() == 0){
cout << "input NULL, no common substring!"<< endl;
}
int i = 0;
int j = 0;
int a[100][100];
//int a[s1.size()+1][s2.size()+1];
string l_substr;
int l_count=0;
int temp;
while(i<s1.size()){
//cout << "entry1" << endl;
        j=0;
while(j<s2.size()){
//cout << "entry2" << endl;
//cout << "i: " << i << "j: " << j << endl;
if(s1[i] == s2[j]){
cout << "match at i: "<< i << " j: " << j << endl;
//cout << "a[i][j] = "<< a[i][j] << endl;
a[i+1][j+1] = a[i][j]+1;
//cout << "a[i+1][j+1]"<< a[i+1][j+1] << endl;
temp = a[i+1][j+1];
cout << "temp: " << temp << endl;
if(temp > l_count){
//new longest count found
l_count = temp;
l_substr = s1.substr(i-temp+1, temp);
cout << "new longest substr found, " << "lcount: " << l_count << endl;
cout << "Substr: " << l_substr << endl;

}
}
j++;
}
i++;
}
cout << "length of longest common substring: " << l_count << endl;
cout << "longenst common substring is: "<< l_substr << endl;
return;
}

int main () {
string s1 = "adfdfdsfahardyadffadsf";
string s2 = "hardyplokmijn";  //o/p shud be hardyharhar
findLongestCommonSubstring(s1, s2);
    return 0;
}



Friday, February 28, 2014

Maximum Subarray Problem, Kadane's algo

The problem has been solved to death many a times(Just go do a simple google search for it) :)

Even then, here is a working C++ implementation of it:
/*
 Copyright: Puneet Sohi. 
 */

#include <iostream>
#include <tr1/unordered_map>
#include <vector>

using namespace std;
using namespace tr1;

void maxSubArr(int *a){
int currIdx = 0;
int maxStartIdx = 0;
int maxStartIdxTillNow = 0;
int maxEndIdx = 0;
int cumSum = 0;
int maxSum = 1; maxSum = maxSum << 31; //make maxSum most negative
int currItem = 0;
while(a[currIdx] != '\0'){
currItem = a[currIdx];
cumSum += currItem;
if(cumSum > maxSum){
maxSum = cumSum;
maxStartIdx = maxStartIdxTillNow;
maxEndIdx = currIdx;
}
else if (cumSum < 0){
cumSum = 0;
maxStartIdxTillNow = currIdx + 1;
}
currIdx++;
}
cout << "max indices: " << maxStartIdx  << " "<< maxEndIdx << endl;
cout << "max sum:  " << maxSum << endl;
return;
}



int main(){
    //Test Cases 
int a[] = {-1, 3, -5, 4, 6, -1, 2, -7, 13, -3};
//int b[] = {3, -1, -1, -1, -1, -1, 2, 0, 0, 0};
//int c[] = {-6,-2,-3,-4,-1,-5,-5};
int d[] = { 3, -1, -1, -1, -1, -1, 2, 0, 0, 0};
//int e[] = {};
//int f[] = {};

    maxSubArr(d);
return 0;

}