1. Horizontal Scanning (Pairwise Prefix Reduction)
Intuition
Set prefix = strs[0]. Iterate i from 1 to strs.length - 1: while strs[i] does not start with prefix, remove the last character from prefix. If prefix becomes empty, return "". Return prefix.
When to apply: Basic functional reduction approach.
Algorithm
- If
strsis empty, return"". - Set
prefix = strs[0]. - For
ifrom 1 tostrs.length - 1: - While
strs[i].indexOf(prefix) != 0: -
prefix = prefix.substring(0, prefix.length - 1) - If
prefixis empty: return"". - Return
prefix.
Horizontal Scanning Pairwise Prefix Reduction Trace
2 of 2 questions left todayObservation: Take the first string strs[0] = "flower" as the initial candidate prefix
Observation: Take the first string strs[0] = "flower" as the initial candidate prefix.
Decision: Sequentially compare this prefix against strs[1] and strs[2], trimming characters from the end until it matches.
Invariant: Prefix is monotonically non-increasing in length.
#include <iostream>#include <string>#include <vector> class Solution {public: std::string longestCommonPrefix(std::vector<std::string>& strs) { if (strs.empty()) return ""; std::string prefix = strs[0]; for (size_t i = 1; i < strs.size(); ++i) { while (strs[i].find(prefix) != 0) { prefix = prefix.substr(0, prefix.size() - 1); if (prefix.empty()) return ""; } } return prefix; }}; int main() { Solution sol; std::vector<std::string> strs = {"flower","flow","flight"}; std::cout << sol.longestCommonPrefix(strs) << std::endl; // "fl" return 0;}Time & Space Complexity
- Time complexity:
O(S) where S is the total number of characters in all strings— In the worst case, all strings are identical and we compare all S characters. - Space complexity:
O(1) auxiliary space
Why Brute Force Doesn't Scale:
Vertical column scanning short-circuits at the minimum prefix divergence point.
Operates in O(1) auxiliary space without constructing intermediate prefix buffers.