ALGORITHMS C++ STL QUIZ

I’d just given this quiz, My 1 question is wrong…
Can you please explain me the question no 2 , 10 and 9.

please also paste the question

Algorithms STL#2

Choose the correct output and time complexity for the following code :

list< int > myList = { 2, 6, 12, 13, 15, 18, 20}; cout << binary_search(myList.begin(), myList.end(), 20) ;

answer:
Output is 1 and time complexity is Linear in size of the list.

linear because it is linked list and
to find mid you have to iterator on list hence linear time complexity

Algorithms STL#10

Given the following code snippet :

string s = “bca”;

do {
cout << s << ’ ';
} while(next_permutation(s.begin(), s.end()));

cout << s;

answer:
Output
bca cab cba abc

i think it is obvious it is just printing next_permutation
even if you have doubt you can ask

Algorithms STL#9

A student just learnt the reverse() function in c++ STL. He writes the following algorithm to check if a given string S is a palindrome.

bool isPalindrome(string& s)
    string rev = s
    reverse(rev.begin(), rev.end())
    return s == rev

Is the algorithm correct? What is the space and time complexity?

answer:

  • Algorithm is correct and uses O(N) time and O(N) extra space.
    o(N) is because we are copying the string into rev
    and algorithm is correct

if you have more doubts regarding this feel free to ask
i hope this helps
if yes hit a like :heart:: and don’t forgot to mark doubt as resolved :grinning:

1 Like

If we apply next_permutation() to the last value, the it will start again from starting??

yes it change s to starting but also return false hence loop terminated

Okay ji, thank you for the help.

bool isPalindrome(string& s) , in this , can you explain how parameter is passing?

it is pass by reference
means no copy is created same string is passed
any change in function reflect back to main as well

okay ji, thank you so much.