Compare Two Lists
Compare the lists like words in a dictionary: look at the first position where they differ. Return -1 if a has the smaller value there, 1 if b does. If one list is a prefix of the other, the shorter one is smaller. If they are identical, return 0.
Linked lists appear in the tests as the list of their values, like [1,2,3]. Each node is a ListNode with .val and .next; the class is already defined for you.
Example 1
a [1,2,3]
b [1,2,4]
returns -1
They first differ at the last node, and 3 < 4.
Example 2
a [1,2]
b [1,2,0]
returns -1
The shorter list is a prefix, so it is smaller.
Constraints
0 <= nodes in each list <= 50-100 <= Node.val <= 100
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.
More Linked lists problems
- Count Distinct ValuesBeginner
- Count Even ValuesBeginner
- Count a Target ValueBeginner
- Count the NodesBeginner
- Count the RisesBeginner
- Differences of NeighborsBeginner
- Everything After a ValueBeginner
- Find a Value's IndexBeginner