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

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;
}
Forward>>
    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