We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Because we're comparing characters in the first half with the characters in the second half of the string. If we go past the midpoint, we will compare the characters again, which is unnecessary.
When we take len(s) // 2, the floor division gives us the middle point of a string that works both if s has odd or even number of characters. E.g. "abcde", 5 // 2 = 2, so we will compare 'a' and 'e' (index 0 and index -1), and then 'b' and 'd' (index 1 and index -2), and we don't need to do anything about 'c' to make a palindrome. For 'abcd', 4 // 2 = 2, we compare 'a' & 'd' and 'b' & 'c' to make a palindrome.
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
The Love-Letter Mystery
You are viewing a single comment's thread. Return to all comments →
Because we're comparing characters in the first half with the characters in the second half of the string. If we go past the midpoint, we will compare the characters again, which is unnecessary.
When we take len(s) // 2, the floor division gives us the middle point of a string that works both if s has odd or even number of characters. E.g. "abcde", 5 // 2 = 2, so we will compare 'a' and 'e' (index 0 and index -1), and then 'b' and 'd' (index 1 and index -2), and we don't need to do anything about 'c' to make a palindrome. For 'abcd', 4 // 2 = 2, we compare 'a' & 'd' and 'b' & 'c' to make a palindrome.