tags: - cocubes - coding - solutions
Coding Solutions and Methods
1. Unit digit of a power
Only the last digit of x matters. Last digits repeat in a short cycle.
Algorithm:
- If y = 0, answer is 1.
- Let d = x MOD 10.
- Use the last-digit cycle for d.
- Select position y MOD cycleLength; use final cycle entry when remainder is zero.
Example: 7 has cycle 7, 9, 3, 1. Unit digit of 7^103 is the third entry because 103 MOD 4 = 3.
2. Card total
Initialise total = 0 and positiveCount = 0. Scan values once. Add every value to total; if value > 0, increment positiveCount.
3. First unique character
- Scan string and count each character.
- Scan again in original order.
- First character with count 1 is answer.
Two scans preserve original ordering.
4. Pair with target sum
Scan left to right. For each x, needed = T โ x. If needed is already in a set, answer exists. Otherwise add x.
Why it works: every earlier value is stored, so when the later member of a valid pair is reached, its complement is found.
5. Valid palindrome
Set left at start and right at end.
- Skip non-alphanumeric characters at both ends.
- Compare lowercased characters.
- If unequal, false.
- Move both inward until they cross.
6. Balanced brackets
Map closing bracket to matching opening bracket.
- Push each opening bracket.
- On closing bracket, stack must be nonempty and top must match; otherwise false.
- End result is true only when stack is empty.
7. Second largest distinct
Maintain largest and secondLargest.
For each x:
- if x > largest: secondLargest = largest; largest = x;
- else if x is distinct from largest and x > secondLargest: secondLargest = x.
Use a sentinel/optional values carefully to support negatives.
8. Equal-half digit substring
For every even length L from largest down to 2:
- For every starting index, compare the digit sum of first L/2 characters with sum of next L/2.
- Return the first valid L.
Use prefix sums to obtain any digit-range sum quickly. For a two-day assessment, write a simple correct version if constraints are modest; optimise only if constraints require it.
9. Count subarrays with sum K
Let prefix be sum so far. A previous prefix equal to prefix โ K identifies a subarray summing to K.
- Start map with count[0] = 1.
- For each x: prefix += x.
- Add count[prefix โ K] to answer.
- Increment count[prefix].
10. Grid shortest path
Use BFS:
- Enqueue start with distance 0 and mark visited.
- Repeatedly remove front cell.
- Explore valid unblocked unvisited up/down/left/right neighbours.
- Enqueue them with distance + 1.
- First time target is removed/reached gives shortest path.
[[05_Coding/Coding_Playbook|Coding playbook]] ยท [[05_Coding/Pattern_Catalog|Pattern catalog]]