Skip to content
Open
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
13 changes: 13 additions & 0 deletions lists/arraylist/arraylist.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,19 @@ func (list *List[T]) Remove(index int) {
list.shrink()
}

// RemoveFirstNElements removes the first n elements from the list.
// if size of list is less than n, no elements are removed.
// O(1) time complexity, ignoring shrinkage.
func (list *List[T]) RemoveFirstNElements(n int) {

if list.Size() < n {
return
}

list.elements = list.elements[n:]
list.shrink()
}

// Contains checks if elements (one or more) are present in the set.
// All elements have to be present in the set for the method to return true.
// Performance time complexity of n^2.
Expand Down
19 changes: 19 additions & 0 deletions lists/arraylist/arraylist_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,25 @@ func TestListRemove(t *testing.T) {
}
}

func TestListRemoveFirstNElements(t *testing.T) {
list := New[string]()
list.Add("a", "b", "c")
list.RemoveFirstNElements(2)
if actualValue, ok := list.Get(0); actualValue != "c" || !ok {
t.Errorf("Got %v expected %v", actualValue, "c")
}

list.RemoveFirstNElements(2) // no effect
if actualValue := list.Size(); actualValue != 1 {
t.Errorf("Got %v expected %v", actualValue, 1)
}

list.RemoveFirstNElements(1)
if actualValue := list.Empty(); actualValue != true {
t.Errorf("Got %v expected %v", actualValue, true)
}
}

func TestListGet(t *testing.T) {
list := New[string]()
list.Add("a")
Expand Down
2 changes: 1 addition & 1 deletion queues/arrayqueue/arrayqueue.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ func (queue *Queue[T]) Enqueue(value T) {
func (queue *Queue[T]) Dequeue() (value T, ok bool) {
value, ok = queue.list.Get(0)
if ok {
queue.list.Remove(0)
queue.list.RemoveFirstNElements(1)
}
return
}
Expand Down