visit
In my previous post: , we talked about how to do Complexity Time and Space analysis, and also see the common Big-O factors with examples.
In this post, I will start talking about Array in depth, and cover some interview questions and hopefully by the end of the reading, you would have a good glance about Array. Once we are familiar with Array, I will talk about String and how to use Array to solve String problems.
Array is a data structure that contains a group of elements. The most basic implementation of an array is a static array. The reason it’s called static is the size is fixed. The read/write access to a certain position is O(1).
class StaticArraydef initialize(length)self.store = Array.new(length)end
# O(1)def [](index)self.store[index]end
# O(1)def []=(index, value)self.store[index] = valueend
protectedattr_accessor :storeend
We create a Dynamic Array from Static Array as follow. The read/write access is also O(1). Let’s implement some general methods i.e. pop(), push(), shift() and unshift() for it. The key here is, when we reach the array size, we want to resize it and double its space, in order to push() or unshift() new elements to the array.
require_relative "static_array"
class DynamicArrayattr_reader :length
def initialize = 0 = 8 = StaticArray.new(8)end
# O(1)def [](index)check_index(index)[index]end
# O(1)def []=(index, value)check_index(index)[index] = valueend
# O(1)def popcheck_index(0) -= 1[length + 1]end
# O(1) amortized; O(n) worst case.def push(val)resize! if == [ + 1] = val += 1end
# O(n): has to shift over all the elements.def shiftcheck_index(0)idx = 0first_el = [0]while idx < - 1[idx] = [idx + 1]idx += 1end -= 1first_elend
# O(n): has to shift over all the elements.def unshift(val)resize! if == idx = while idx > 0[idx] = [idx - 1]idx -= 1end[0] = val += 1end
protectedattr_accessor :capacity, :storeattr_writer :length
def check_index(index)raise "out of bounds" if ( < index + 1 || index < 0)end
# O(n): has to copy over all the elements to the new store.def resize!new_store = StaticArray.new( * 2)idx = 0while idx < new_store[idx] = [idx]idx += 1end = new_store *= 2endend
If you read carefully enough, you would notice there is a keyword “amortized” in the code snippet. What does that mean? When we want to append (or push) a new element to the Array and it reaches its size limit, we want to double the size. However, resize!
method allocates a larger region, moves the whole array, and deletes the previous. This is a O(n)
operation. But if we're only doing it every O(1/n)
times, then on average it can still come out to O(n * 1/n) = O(1)
. That’s called amortized cost.
In average and worst cases,
Access O(1)
Search O(n)
Insertion O(n)
(at the end of Array is O(1) amortized, at the beginning or middle of Array is O(n)
Deletion O(n)
Space O(n)
We now know accessing an element in Array is fast (O(1)
), whereas searching/adding/removing is relatively slow (O(n)
), which sometimes requires looping through the whole array.
It is a data structure that uses a Static Array as if it were connected end-to-end.
require_relative "static_array"
class RingBufferattr_reader :length
def initialize = 0 = 8 = 0 = StaticArray.new()end
# O(1)def [](index)check_index(index)ring_index = (index + ) % [ring_index]end
# O(1)def []=(index, val)check_index(index)ring_index = (index + ) % [ring_index] = valend
# O(1)def popcheck_index(0) -= 1;val = [( + ) % ][( + ) % ] = nilvalend
# O(1) amortizeddef push(val)resize! if == [( + ) % ] = val += 1end
# O(1)def shiftcheck_index(0)val = [][] = nil = ( + 1) % -= 1valend
# O(1) amortizeddef unshift(val)resize! if == = ( - 1) % [] = val += 1valend
protectedattr_accessor :capacity, :start_idx, :storeattr_writer :length
def check_index(index)raise "index out of bounds" if (index < 0 || index > - 1)end
def resize!new_store = StaticArray.new( * 2)idx = 0while idx < new_store[idx] = [( + idx) % ]idx += 1end = new_store = 0 *= 2endend
To master Array data structure and questions, we at least need to be very familiar with:
Some advantages of using Array:
● Constant time access and allows random access
● Grouping like items
And some disadvantages…
● Insertion and deletion can be expensive for large arrays
● Dynamic arrays have cost to resize, and limited by the size allocated
Enough said, here are some popular interview questions for your practice:
0
's to the end of it while maintaining the relative order of the non-zero elements. ()Now we know about Array, let’s talk about String — which is nothing but a Character-based Array. You just need to learn techniques to solve Array questions, and you are a String Master by nature!
Before diving into String related questions, we need to get familiar with:
In my , I will talk about Data Structures for Queue, Stack and Linked List.
There’s no better way to support me than to give me a follow on Medium (). Let me know that I should write more!
Did you know that you can give up to 50 👏’s by pressing down on the 👏 button? Give it a try if you reeeeeeally liked this article!