diff --git a/1_arrays_and_hashing/6_encode_and_decode_strings/solution.go b/1_arrays_and_hashing/6_encode_and_decode_strings/solution.go new file mode 100644 index 0000000..a48f168 --- /dev/null +++ b/1_arrays_and_hashing/6_encode_and_decode_strings/solution.go @@ -0,0 +1,40 @@ +package encodeanddecodestrings + +import ( + "strconv" + "strings" +) + +// Time complexity: O(n), where n is the total length of all strings in the input slice. +// Space complexity: O(n) +func Encode(strs []string) string { + var sb strings.Builder + for _, str := range strs { + sb.WriteString(strconv.Itoa(len(str))) + sb.WriteString("#") + sb.WriteString(str) + } + return sb.String() +} + +// Time complexity: O(n), where n is the total length of the encoded string. +// Space complexity: O(n) +func Decode(s string) []string { + if len(s) == 0 { + return []string{} + } + var result []string + i := 0 + for i < len(s) { + j := i + for s[j] != '#' { + j++ + } + length, _ := strconv.Atoi(s[i:j]) + j++ + str := s[j : j+length] + result = append(result, str) + i = j + length + } + return result +} diff --git a/1_arrays_and_hashing/6_encode_and_decode_strings/solution_test.go b/1_arrays_and_hashing/6_encode_and_decode_strings/solution_test.go new file mode 100644 index 0000000..e2102be --- /dev/null +++ b/1_arrays_and_hashing/6_encode_and_decode_strings/solution_test.go @@ -0,0 +1,32 @@ +package encodeanddecodestrings + +import ( + "reflect" + "testing" +) + +func TestEncodeDecode(t *testing.T) { + cases := []struct { + name string + input []string + expected []string + }{ + {"Basic strings", []string{"hello", "world"}, []string{"hello", "world"}}, + {"Empty strings", []string{"", "", ""}, []string{"", "", ""}}, + {"Strings with special characters", []string{"a#b", "c$d", "e^f"}, []string{"a#b", "c$d", "e^f"}}, + {"Mixed lengths", []string{"short", "", "a", "longerstring"}, []string{"short", "", "a", "longerstring"}}, + {"Single string", []string{"onlyone"}, []string{"onlyone"}}, + {"Empty list", []string{}, []string{}}, + } + + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + encoded := Encode(c.input) + decoded := Decode(encoded) + + if !reflect.DeepEqual(decoded, c.expected) { + t.Errorf("Decode(Encode(%v)) = %v; want %v", c.input, decoded, c.expected) + } + }) + } +}