Strings and Arrays

Arrays

An array is a data structure that holds a fixed number of objects of the same type. Because arrays have fixed sizes, they are highly efficient for quick lookup regardless of the array size. However, there is a tradeoff with this fast access time; any insertion or deletion from the middle of the array requires moving the rest of the elements to fill in or close the gap. To optimize time efficiency, try to add and delete mostly from the end of the array.

Arrays commonly come up in interviews, so it's important to review the array library for the language you code in.

Tips:

  • Off-by-one errors can often happen with arrays, so be wary of potentially over indexing as it will throw an error
  • Try to add elements to the back of an array instead of the front, as adding to the front requires shifting every element back
  • In Java, arrays are a fixed size so consider utilizing an ArrayList instead if you need to dynamically alter the size of the array.

Strings

Strings are a special kind of array, one that only contains characters. They commonly come up in interview questions, so it's important to review the string library for the language you're most comfortable with. You should know common operations such as: getting the length, getting a substring, splitting a string based on a delimiter, etc.

It's important to note that whenever you manipulate a string, a new copy of the string is created. There are different ways to reduce the space utilized depending on the language:

  • In Python, you can represent a string as a list of characters and operate on the list of character instead by using join(). Read about this operation here.
  • In Java, you can utilize the StringBuffer class to mitigate the amount of space utilized if you need to manipulate a string.

Patterns List

Strings Resources

General guide

Strings in C++

Arrays Resources

General guide

Python arrays

Java arrays

Fork me on GitHub