interview-preparation / what-we-do

0 stars 8 forks source link

[Big-O] Additional Problems #11 #35

Closed rygh4775 closed 5 years ago

rygh4775 commented 5 years ago

The following code prints all strings of length k where the characters are in sorted order. It does this by generating all strings of length k and then checking if each is sorted. What is its runtime?

int numChars = 26;

void printSortedStrings(int remaining) {
    printSortedStrings(remaining, "");
}

void printSortedStrings(int remaining, String prefix) {
    if (remaining == 0) {
        if (islnOrder(prefix)) {
            System.out.println(prefix);
        }
    } else {
        for (int i = 0; i < numChars; i++) {
            char c = ithLetter(i);
            printSortedStrings(remaining - 1, prefix + c);
        }
    }
}

boolean islnOrder(String s){
    for (int i = 1; i < s.length(); i++) {
        int prev = ithLetter(s.charAt(i - 1));
        int curr = ithLetter(s.charAt(i));
        if (prev > curr) {
            return false;
        }
    }
    return true;
}

char ithLetter(int i){
    return (char) (((int) 'a') + i);
}
RoyMoon commented 5 years ago

0(kc^k) where k is the length of the string and c is 26, Loop c 를 k time 부르게 되고요 islnOrder 함수에서 k time loop 가 있습니다.