Hamed Kiani (Ph.D.)
  • Home
  • Publications
  • Contact

A method isSubstring which checks if one word is a substring of another, use this method to check if two strings are rotated.

7/20/2015

3 Comments

 
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
/******************************************************************************************
*******************************************************************************************
Chapter 1 Arrays and Strings

 * Assume you have a method isSubstring which checks if one word is a substring of another.
 * Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 using
 * only one call to isSubstring (i.e., "waterbottle" is a rotation of "erbottlewat")
 
By: Hamed Kiani (July 20, 2015)
******************************************************************************************
******************************************************************************************/

#include<iostream>
#include<cstring>

using namespace std;

bool is_sub_string(const char* s1, const char* s2)
{
        // check if two strings are not null
        if (!s1 || !s2)
                return false;
        // find the first char of s2, s2[0] in the s1, if found then check the rest of s2 over s1
        int i,j ;
        j = 0;
        for (i = 0; s1[i] != '\0'; i++)
        {
                if (s1[i] == s2[0]) {
                        for(j = 1; s2[j] != '\0'; j++)                    
                                // we are already sure that s1[i] == s2[0]
                                if (s2[j] != s1[i+j])
                                        break;
                }
                // if (s2[j] == '\0') means that we have similar chars till the end of s2
                if (s2[j] == '\0')
                        return true;
        }
        // is not s sub string
        return false;
}

// O(n) time, O(1) additional space.
bool is_rotation_fun1(const char* s1, const char* s2)
{
        if (!s1 || !s2)
                return false;
        if (strlen(s1) != strlen(s2))
                return false;

        while(*s2 != '\0')
                s2++;
        s2--;
        while(*s1 != '\0')
        {
                if (*s1 != *s2)
                        return false;
                s1++; s2--;
        }       
        return true;
}

// O(n) time, O(n) additional space.
// using is_rotation function
// the trick is that we append the inverse of s1 to s1 and then check:
// if is_sub_string(s1+inv(s1[1:length(s1)-1]), s2).
// name + man = nameman
// is is_sub_string(nameman, eman)
bool is_rotation_fun2(  char* s1,   char* s2)
{
        int l1;
        l1 = strlen(s1);            
        char* temp = (char *) malloc( sizeof(char) * l1 * 2);
        char *t1 = s1;   
        int i = 0;
        while(*t1 != '\0')
        {
                temp[i] = *t1;
                t1++; i++;
        }
        // move t1 pointin to end of s1 to next to last char. 
        // accordingly, we change l1 = l1 -2, since we ignore the last char of s1 
        //and consider length counter as [0...strlen(s1)-1]
        t1 -= 2; l1 -= 2;
        while(l1>=0)
        {
                temp[i] = s1[l1];
                l1--; i++;
        }       
        bool check = is_sub_string(temp, s2);
        free(temp);
        return check;
}

void main() {
        char str1[] = "check this string";
        char str2[] = "this";
        bool check ;
        check = is_sub_string(str1,str2);
        cout << check << endl;

        char str3[] = "siht";
        check = is_rotation_fun1(str3, str2);
        cout << check << endl;

        check = is_rotation_fun2(str3, str2);
        cout << check << endl;
}
3 Comments

If an element in an M * N matrix is 0, set its entire row and column to 0 (c++)

7/20/2015

0 Comments

 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/******************************************************************************************
*******************************************************************************************
Chapter 1 Arrays and Strings

 * Write an algorithm such that if an element in an M * N matrix is 0,
 * its entire row and column is set to 0;
 
By: Hamed Kiani (July 20, 2015)
******************************************************************************************
******************************************************************************************/

#include<iostream>
#include<cstring>

using namespace std;

const int row = 3, col = 3;

void print_mat(double **mat, int row, int col)
{
        for (int i = 0; i < row; i++) {
                for (int j = 0; j < col; j++)
                        cout << " " << mat[i][j];
                cout << endl;
        }
}

// space O(n), time O(n^2)
void zero_in_matrix(double **mat)
{
        
        // int zero_row = (int) malloc(sizeof(int) * row)
        int zero_row[row] = {0};
        //int *zero_row = (int*) malloc(sizeof(int) * row);
        
        // int zero_col = (int) malloc(sizeof(int) * col)
        int zero_col[col] = {0};
        //int *zero_col = (int*) malloc(sizeof(int) * col);

        // keep the indices of zero values in mat
        for (int i = 0 ; i < row; i++)
                for (int j = 0 ; j < col; j++)
                {
                        if (mat[i][j] == 0){
                                zero_row[i] = 1;
                                zero_col[j] = 1;
                        }
                }
        
        // che if there is a zero, change all values of the colum and row to zero
        for (int i = 0 ; i < row; i++)
                for (int j = 0 ; j < col; j++)
                {
                        if ((zero_row[i] == 1) | (zero_col[j] == 1))
                                mat[i][j] = 0;
                }
}

void main() {

        double **mat;
        //int col, row;

        cout << " # or rows: " << row << endl;
        // cin >> row;

        cout << " # or cols: " << col << endl;
        // cin >> col;


        mat = (double **) malloc(sizeof(double *) * row);
        
        for (int i = 0; i < row; i++)
                mat[i] = (double *) malloc(sizeof(double) * col);

        for (int i = 0; i < row; i++)
                for (int j = 0; j < col; j++)
                        cin >> mat[i][j];

        cout << " the original matrix: " << endl;
        print_mat(mat, row, col);

        zero_in_matrix(mat);

        cout << " the matrix after zeroing: " << endl;
        print_mat(mat, row, col);       
}
0 Comments

Replace all spaces in a string with '%20' (c++)

7/16/2015

2 Comments

 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/******************************************************************************************
*******************************************************************************************
Chapter 1 Arrays and Strings

 * Replace all spaces in a string with '%20'
 
By: Hamed Kiani (July 16, 2015)
******************************************************************************************
******************************************************************************************/

#include<iostream>
#include<cstring>

using namespace std;


// Replace inplace , time: O(n), additional space: O(1)

void replace_space_with_20(char *str)
{
        // return if str is NULL 
        if (!str)
                return;
        // get the length of the str and the number of spaces
                int l = 0, nos = 0;
                // Q:how to write with a for loop?
                while (str[l] != '\0')
                {
                        if (str[l] == ' ')
                                nos++;
                        l++;
                }
                cout << "the length of str is " << l << " with " <<  nos << " spaces " << endl;
                // the length of the new string, why not (nos*3)? ;-)
                int newl = (nos*2) + l;               
                cout << " the new length is : " << newl << endl;
                // extend the original str to have the new length
                // Q: why newl--?
                str[newl--] = '\0';
                l--;
                while(newl >= 0)
                {
                        if (str[l] == ' ')
                        {
                                str[newl--] = '0';
                                str[newl--] = '2';
                                str[newl--] = '%';
                                l--;
                        }
                        else
                                str[newl--] = str[l--];
                }
}
// Q: how can you write the above function using additional buffer? 
// how about the time and space complexity?

// Test it!
int main()
{
        char str[] = {"replace the spaces with 20% !"};     
        cout << "original str: " << str << "with the length of "<< strlen(str) << endl;
        replace_space_with_20(str);     
        cout << "the new str: " << str << "with the length of "<< strlen(str) << endl;
        return 0;
}
2 Comments

Are two strings anagram?

7/15/2015

 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/******************************************************************************************
*******************************************************************************************
Chapter 1 Arrays and Strings

* Are two strings anagram? 

By: Hamed Kiani (July 15, 2015)
******************************************************************************************
******************************************************************************************/

#include "stdafx.h"
#include <iostream>
#include <cstring>
using namespace std;

// additional space: O(n), time: O(n)
// how about merge sort with time of O(n log n) and no additional space?

bool are_anagram(char *s1, char *s2)
{
        // return false if null
        // return false for strings with different length
        if (!s1 || !s2)
                return false;
        if (strlen(s1) != strlen(s2))
                return false;
        int count[256] = { 0 };
        for (int i = 0; s1[i] != '\0'; i++)
        {
                count[(int) s1[i]]++;
                count[(int) s2[i]]--;                 
        }

        for (int i = 0; i < 256; i++)
        if (count[i] > 0)
                return false;
        return true;
}
 

int main()
{                
        char s1[] = "mai setin tg twostrings !";
        char s2[] = "i am testing two strings!";

        bool check = are_anagram(s1, s2);
        if (check)
                cout << s1 << " and " << s2 << " are angram " << endl;
        else
                cout << s1 << " and " << s2 << " are not angram " << endl;
        return 0;
}

Remove duplicate chars from string (c++)

7/15/2015

 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/******************************************************************************************
*******************************************************************************************
Chapter 1 Arrays and Strings

 * Remove duplicate characters in a string.
 
By: Hamed Kiani (July 15, 2015)
******************************************************************************************
******************************************************************************************/

#include<iostream>
#include<cstring>

using namespace std;


// remove inplace , time: O(n^2), additional space: O(1)

void rem_dup_str(char *str)
{
        // return if str is NULL or str.length< 2
        if (!str)
                return;
        if (strlen(str) < 2)
                return;
        // end: keeps the end of the string with no dulicate, is initialized to 1.
        // i : is the counter on the str length
        // j looks for any duplicate char from the first char of string till "end";
        // str[end] = '\0' sets the rest of string which may contain redundant chars

        int j, end = 1;
        for (int i = 1; str[i] != '\0' ; i++){
                for (j = 0; j<end; j++)
                        if (str[i] == str[j])
                                break;
                                if (j == end)
                                        str[end++] = str[i]; // do not change the 
        }
        str[end] = '\0';
}

// remove by buffer , time: O(n), additional space: O(n)

void rem_dup_str_buffer(char *str)
{
        if (!str)
                return;
        // keep the end of non-duplicated string by "end"
        // dup[256] is true is the corresponding char was seen before
        // works for all ASCII chars. 

        int end = 0;
        bool dup[256] = {false};
        for (int i = 0; str[i] != '\0'; i++)
        {
                if (dup[(int) str[i]])                    
                        continue;
                else
                {
                        dup[(int) str[i]] = true;
                        str[end++] = str[i];                    
                }
        }
        str[end] = '\0';
}

// Test it!
int main()
{
        char str[] = "Remove dublicate chars from string!"; 
        cout << "original str: " << str << endl;
        rem_dup_str_buffer(str);
        cout << "after removing duplicate chars: " << str << endl;
        return 0;
}

Reverse a c-string string (c++)

7/15/2015

 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/******************************************************************************************
*******************************************************************************************
Chapter 1 Arrays and Strings

 * Reverse a c-string string.
 
By: Hamed Kiani (July 14, 2015)
******************************************************************************************
******************************************************************************************/

#include<iostream>

using namespace std;


// inplace reverse, time: O(n), space: O(1)
// Challenge: write this function using array instead of pointers. 

void reverse_str(char *str)
{
        char * tail = str;       
        while (*tail !='\0')
                tail++;
        tail--;
        char tmp;
        while(tail>str)
        {
                tmp = *str;
                *str++ = *tail;
                *tail-- = tmp;              
        }       
}

// Test it!
int main()
{
        char str[] = "Reverse this string!";        
        cout << "original str: " << str << endl;
        reverse_str(str);
        cout << "reversed str: " << str << endl;
        return 0;
}

Determine if a string has all unique characters (c++)

7/14/2015

 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/******************************************************************************************
*******************************************************************************************
Chapter 1 Arrays and Strings

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

By: Hamed Kiani (July 14, 2015)
******************************************************************************************
******************************************************************************************/

#include<iostream>

using namespace std;

// method 1:
// using bit shifting, time: O(n), space: O(1)
// only for string in [a-z], 28 chars
// 1 (int) is a 4 bytes (32 bits) to count the presence of 28 chars
// challenge: how to re-write this function to work for all 256 ASCII chars??

bool string_unique_bit(char *str)
{
        int check = 0;
        int i = 0;    // counter over the string
        // '/0' indicates the end of a c-string
        while(str[i] != '\0')
        {
                // (int) str[i]: cast the char to int; (int)'a' = 97
                int pos = (int) str[i] - 'a';
                // (1 << pos) shifts the bit representation of 1 (32 bits) to left by pos-steps
                // if ((check & (1 << pos)) >0 ) means that current char was seen before
                if ((check & (1 << pos)) >0 )                     
                        return false;
                // keeping the presence of each char in check
                check |= (1 << pos);
                // process the next char
                i++;
        }
        return true;
}


// method 2:
// using an aditional buffer to keep the history of each seen char
// time: O(n), space: O(n)
// works for all ASCII chars: 0-255
// challenge: how to write this function without using i?

bool string_unique(char * str)
{
        // check is a bool array of 256, initialized as false      
        bool check[256] = {false};
        int i = 0;
        while(str[i] != '\0')
        {
                if (check[(int) str[i]])
                        // current char was seen before, 
                        return false;
                else
                {
                        check[(int) str[i]] = true;
                        i++;
                }
        }
}

// Test it!
int main()
{
        char * str;
        str = "hamed";
        bool check;
        check = string_unique(str);
        if (check)
                cout << str << " has all unique chars"  << endl;
        else
                cout << str << " does not have unique chars"  << endl;   
        return 0;
}
    A place to practice the coding interview.

    Author

    Hamed Kiani

    Categories

    All
    Arrays And Strings
    Linked List
    Stack And Queue
    Trees And Graphs

    Archives

    September 2015
    July 2015

    RSS Feed

Copyright © 2020, Hamed Kiani