Can you write a function to solve a classic algorithmic problem and explain its Big O complexity? Implement edit_distance(word1, word2) to return the minimum number of single-character insertions, deletions, or substitutions required to transform word1 into word2. Inputs are strings and the output is an integer. For example, edit_distance("horse", "ros") returns 3, while edit_distance("", "abc") returns 3; explain the time and space complexity.
def edit_distance(word1, word2):