Given a string s, compress it by replacing any consecutive repetition of a substring with the form k{pattern} where k > 1 and pattern may itself be recursively encoded. Return the shortest possible encoded string; if no encoding shortens s, return s unchanged. Clearly define the encoding rules, implement a function encode(s) that outputs the minimal-length encoding, and analyze time and space complexity. Discuss how you detect repeat structure, handle nested encodings, and avoid redundant work.