String processing and parsing coding interview questions
Four string-processing coding questions in Java and Python, from substring search and word reversal to palindromes and atoi.
Palindromes and substring search
Expand around centers, and scan for the first occurrence of a needle.
1.1 Longest Palindromic Substring Medium 3 min
I try every index as a palindrome center and expand left and right while the characters match. I do this once for odd-length palindromes and once for even-length ones, and I keep the longest span I find. That is quadratic time and constant extra space.
Read the full answer1.2 Find the Index of the First Occurrence in a String Easy 3 min
I slide the needle along the haystack and compare characters at each starting index until the needle matches or I run out of room. That is a straightforward O(n m) scan. If I need linear time I would mention Knuth-Morris-Pratt, but the two-loop search is what I implement first.
Read the full answer1.3 Reverse Words in a String Medium 3 min
I split the string on whitespace, drop empty pieces, reverse the list of words, and join them with a single space. That trims leading and trailing spaces and collapses repeats in the middle. You can also reverse the whole character array and then reverse each word in place.
Read the full answer1.4 String to Integer (atoi) Medium 5 min
I skip leading spaces, read an optional plus or minus, then accumulate digits until I hit a non-digit or the end. If the running value would move outside the 32-bit signed range, I clamp it to that range and stop. Anything after the first invalid character is ignored.
Read the full answer