S1Q1 · Extract Border Elements from a List¶
⚡ Quick Reference
Function: extract_border_elements(arr: list) -> list
Core idea: handle three cases - empty, single element, multiple elements.
def extract_border_elements(arr: list) -> list:
if len(arr) == 0:
return []
if len(arr) == 1:
return [arr[0]]
return [arr[0], arr[-1]]
Key rules:
- Empty list → []
- Single element → [arr[0]]
- Two or more elements → [arr[0], arr[-1]]
Problem Statement¶
Problem
Write a function extract_border_elements(arr) that returns a list with the first and last elements of the input list, handling edge cases for empty and single-element lists.
Examples:
[1, 2, 3, 4]
[1, 4]
[5]
[5]
[]
[]
[7, 8, 9, 10, 11]
[7, 11]
Tracing all examples¶
| Input | Length | Case | Output |
|---|---|---|---|
[1, 2, 3, 4] |
4 | > 1 | [arr[0], arr[-1]] = [1, 4] ✓ |
[5] |
1 | == 1 | [arr[0]] = [5] ✓ |
[] |
0 | == 0 | [] ✓ |
[7, 8, 9, 10, 11] |
5 | > 1 | [7, 11] ✓ |
Solution approaches¶
Key takeaways¶
Handle edge cases first
Check empty and single-element cases before the general case. This avoids index errors and keeps the logic flat - no nested conditions needed.
arr[-1] for the last element
Negative indexing always gives the last element regardless of list length. arr[-1] is cleaner than arr[len(arr)-1] and works for any non-empty list.
if not arr - Pythonic empty check
Empty lists are falsy in Python. if not arr is the idiomatic way to check for an empty list - equivalent to if len(arr) == 0 but shorter.