You can implement data structures using "Objects". Objects are just HashMaps but with nicer syntax.
For interviews we usually prefer implementing data structures with HashMaps instead of Objects. For example, here's how we'd make a LinkedList:
But instead of using HashMaps, you might want (or be told) to implement a data structure using objects. Here's how you might implement the above code using objects. We'll assume we already wrote the class ListNode
.
Objects like node1
, node2
, and node3
behave exactly the same as HashMaps. They just have different syntax and let you write less code sometimes. Anything you do with an object, you could have done with a HashMap and functions instead. It's just a matter of preference which to use.
Now that you know about objects, we'll walk you through classes, which create objects.
There are only 2 things about classes you need to know.
1. You can write a function that runs when you create a new object, like when you call x = ListNode()
. The function is always called __init__
.
2. When you define a new function in a Class, you need to give the function an extra input. People usually call it the self
input. This input gives you access to the object you're dealing with. It's automatically passed in, and you don't have to specify it when you actually call the function.
Here's an example of a Class:
And here's an example of how you use this Class:
TreeNode.of
function can be used to create an entire binary tree using 1 line of code. The input is a BFS traversal of the tree including nulls, and the output is the root node of the tree.TreeNode.of([1, None, 2, None, 3])
ListNode.of
function lets you create an entire Linked List using 1 line of code. The input is an array, and the output is the head of the Linked List.ListNode.of([1, 2, 3])
ListNode.of([1, 2, 3], 1)
GraphNode.of
function lets you create an entire Graph using 1 line of code. The input is an Adjacency Matrix, and the output is the first node in the matrix.GraphNode.of([ ['A', 1, 2], ['B', 2], ['C', 0] ])
[['__init__', 15], ['add', 16], ['get']]
c = MyClass(15) c.add(16) c.get()