Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions 1_arrays_and_hashing/6_encode_and_decode_strings/solution.go
Original file line number Diff line number Diff line change
@@ -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
}
32 changes: 32 additions & 0 deletions 1_arrays_and_hashing/6_encode_and_decode_strings/solution_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
})
}
}
Loading