0% found this document useful (0 votes)
22 views10 pages

Enphase InterviewQ

The document outlines various coding problems categorized into easy, medium, and difficult levels, including their problem statements, example inputs and outputs, solutions, and evaluation points. Key problems include implementing a shopping cart feature to find two product prices that sum to a target, creating a class method to track resource access, and designing an LRU cache. Each problem emphasizes efficient coding practices and handling edge cases.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views10 pages

Enphase InterviewQ

The document outlines various coding problems categorized into easy, medium, and difficult levels, including their problem statements, example inputs and outputs, solutions, and evaluation points. Key problems include implementing a shopping cart feature to find two product prices that sum to a target, creating a class method to track resource access, and designing an LRU cache. Each problem emphasizes efficient coding practices and handling edge cases.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Easy Questions

1.​ Two Sum


Problem Statement :
You’re building a shopping cart feature. Given a list of product prices (⁠nums ⁠) and a target total
(⁠target ⁠), find two distinct products whose prices add up to the target. Return their indices. Assume
exactly one solution exists.

Example :
Input: nums = [50, 20, 30, 10], target = 80
Output: [0, 2] # Prices 50 + 30 = 80

Solution :
def two_sum(nums, target):
seen = {}
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], i]
seen[num] = i
return []

Test Case
print(two_sum([50, 20, 30, 10], 80)) # Output: [0, 2]

Evaluation Points :
•⁠ ⁠Handles edge cases (e.g., negative prices, duplicate values).
•⁠ ⁠Efficiently uses a hash map for O(n) time.

Live Coding Tips : Ask, “What if there are duplicate prices?” (Solution works fine.)

2.​ Class Method Counter


Problem Statement :
Your team needs to track how many times a shared resource (e.g., a database connection) is accessed
across all instances of a ⁠ResourceTracker ⁠class. Implement a class method ⁠increment() ⁠that maintains
a count of total accesses.

Example :
tracker1 = ResourceTracker()
tracker2 = ResourceTracker()
print(tracker1.increment()) # Output: 1
print(tracker2.increment()) # Output: 2
Solution :
class ResourceTracker:
_total_accesses = 0

@classmethod
def increment(cls):
cls._total_accesses += 1
return cls._total_accesses

Test Case
tracker1 = ResourceTracker()
tracker2 = ResourceTracker()
print(tracker1.increment()) # Output: 1
print(tracker2.increment()) # Output: 2

Evaluation Points :
•⁠ ⁠Understands class variables vs. instance variables.
•⁠ ⁠Correctly uses ⁠@classmethod ⁠.

Live Coding Tips : Ask, “How would you reset the counter?” (Add a ⁠@classmethod reset() ⁠.)

3.​ File Line Reverser


Problem Statement :
You’re debugging a log file where the most recent entries are appended at the end. Write a function
⁠reverse_file_lines(input_file, output_file) ⁠that reverses the order of lines (last line becomes first) and
saves them to a new file.

Example Input File (⁠logs.txt ⁠) :


Error: Invalid input
Warning: Low disk space
Info: System started

Expected Output File (⁠reversed_logs.txt ⁠) :


Info: System started
Warning: Low disk space
Error: Invalid input

Solution :
def reverse_file_lines(input_file, output_file):
with open(input_file, 'r') as f:
lines = f.readlines()
with open(output_file, 'w') as f:
f.writelines(reversed(lines))

Test Case
reverse_file_lines('logs.txt', 'reversed_logs.txt')

Evaluation Points :
•⁠ ⁠Handles file I/O safely (uses context managers).
•⁠ ⁠Preserves line endings and whitespace.

Live Coding Tips : Ask, “How would you handle a 10GB file?” (Read line by line, store offsets.)
Medium Questions
1.​ Valid Parentheses
Problem Statement :
You’re building a JSON validator. Given a string containing only ⁠(){}[] ⁠, determine if the brackets are
balanced.

Examples :
Input: "()[]{}" → Output: True
Input: "(]" → Output: False
Input: "([)]" → Output: False

Solution :
def is_valid(s: str) -> bool:
stack = []
mapping = {')': '(', '}': '{', ']': '['}
for char in s:
if char in mapping:
top = stack.pop() if stack else '#'
if mapping[char] != top:
return False
else:
stack.append(char)
return not stack

Test Cases
print(is_valid("()[]{}")) # True
print(is_valid("([)]")) # False

Evaluation Points :
•⁠ ⁠Uses a stack to track opening brackets.
•⁠ ⁠Handles edge cases (empty string, unmatched brackets).

Live Coding Tips : Ask, “How would you extend this to support ⁠<angle> ⁠brackets?” (Add to
⁠mapping ⁠).

2.​ Binary Tree Level Order Traversal


Problem Statement :
You’re analyzing a company’s org chart (binary tree). Print employees level by level, grouped by
hierarchy.
Example Tree :
CEO
/ \
CTO CFO
/ /\
Eng Acc HR

Expected Output :
[ ['CEO'], ['CTO', 'CFO'], ['Eng', 'Acc', 'HR'] ]

Solution :
from collections import deque

class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right

def level_order(root: TreeNode) -> list[list[int]]:


if not root:
return []
queue = deque([root])
result = []
while queue:
level = []
for _ in range(len(queue)):
node = queue.popleft()
level.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
result.append(level)
return result

Test Case
root = TreeNode('CEO',
TreeNode('CTO', TreeNode('Eng')),
TreeNode('CFO', TreeNode('Acc'), TreeNode('HR')))
print(level_order(root))

Evaluation Points :
•⁠ ⁠Uses BFS with a queue to traverse levels.
•⁠ ⁠Handles edge cases (empty tree, single-node tree).

Live Coding Tips : Ask, “How would you print levels in reverse?” (Append to result with ⁠insert(0,
level) ⁠).

3.​ Merge Intervals


Problem Statement :
You’re optimizing a calendar scheduler. Given a list of meeting intervals ⁠[start, end] ⁠, merge
overlapping intervals.

Examples :
Input: [[1, 3], [2, 6], [8, 10]] → Output: [[1, 6], [8, 10]]
Input: [[1, 4], [4, 5]] → Output: [[1, 5]]

Solution :
def merge(intervals: list[list[int]]) -> list[list[int]]:
intervals.sort(key=lambda x: x[0])
merged = []
for interval in intervals:
if not merged or merged[-1][1] < interval[0]:
merged.append(interval)
else:
merged[-1][1] = max(merged[-1][1], interval[1])
return merged
Test Cases
print(merge([[1, 3], [2, 6], [8, 10]])) # [[1, 6], [8, 10]]
print(merge([[1, 4], [4, 5]])) # [[1, 5]]

Evaluation Points :
•⁠ ⁠Sorts intervals first for O(n log n) time.
•⁠ ⁠Handles edge cases (empty list, non-overlapping intervals).

Live Coding Tips : Ask, “What if intervals are unsorted?” (Clarify sorting is allowed).
Difficult Questions
1.​ LRU Cache
Problem Statement :
You’re designing a caching system for a web server. Implement an LRU (Least Recently Used) cache
with:
•⁠ ⁠get(key) ⁠: Return the value if exists, otherwise ⁠-1 ⁠.
•⁠ ⁠put(key, value) ⁠: Add/update the value. Evict the least recently used item if capacity is exceeded.

Constraints :
•⁠ ⁠Operations must be O(1) time.
•⁠ ⁠Capacity is fixed at initialization.

Example :
cache = LRUCache(2)
cache.put(1, 10) # Cache: {1=10}
cache.put(2, 20) # Cache: {1=10, 2=20}
cache.get(1) # Returns 10, Cache: {2=20, 1=10}
cache.put(3, 30) # Evicts 2, Cache: {1=10, 3=30}

Solution :
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity: int):
self.cache = OrderedDict()
self.capacity = capacity

def get(self, key: int) -> int:


if key not in self.cache:
return -1
self.cache.move_to_end(key) # Mark as recently used
return self.cache[key]

def put(self, key: int, value: int) -> None:


if key in self.cache:
self.cache.move_to_end(key)
self.cache[key] = value
if len(self.cache) > self.capacity:
self.cache.popitem(last=False) # Evict least recently
used
Test Case
cache = LRUCache(2)
cache.put(1, 10)
cache.put(2, 20)
print(cache.get(1)) # 10
cache.put(3, 30)
print(cache.get(2)) # -1 (evicted)

Evaluation Points :
•⁠ ⁠Uses ⁠OrderedDict ⁠for O(1) operations.
•⁠ ⁠Correctly evicts LRU items when capacity is reached.

Live Coding Tips : Ask, “How would you handle thread safety?” (Add locks in a real system).

2.​ Cycle Detection (Course Schedule)


Problem Statement :
You’re building a course prerequisite checker. Given ⁠num_courses ⁠and a list of ⁠[course, prerequisite] ⁠
pairs, determine if all courses can be finished (no cycles).

Examples :
Input: num_courses = 2, prerequisites = [[1, 0]] → Output: True
Input: num_courses = 2, prerequisites = [[1, 0], [0, 1]] → Output: False (cycle)

Solution (Topological Sort) :


from collections import deque
def can_finish(num_courses: int, prerequisites: list[list[int]]) ->
bool:
graph = [[] for _ in range(num_courses)]
in_degree = [0] num_courses
for course, prereq in prerequisites:
graph[prereq].append(course)
in_degree[course] += 1

queue = deque([i for i in range(num_courses) if in_degree[i] ==


0])
count = 0
while queue:
node = queue.popleft()
count += 1
for neighbor in graph[node]:
in_degree[neighbor] -= 1
if in_degree[neighbor] == 0:
queue.append(neighbor)
return count == num_courses

Test Cases
print(can_finish(2, [[1, 0]])) # True
print(can_finish(2, [[1, 0], [0, 1]])) # False

Evaluation Points :
•⁠ ⁠Detects cycles using Kahn’s algorithm (BFS + in-degree counting).
•⁠ ⁠Handles edge cases (no prerequisites, disconnected graph).

Live Coding Tips : Ask, “What if the graph is disconnected?” (Still works—counts reachable
nodes).

3.​ Longest Increasing Subsequence (LIS)


Problem Statement :
You’re analyzing stock prices over time. Find the length of the longest increasing subsequence (not
necessarily contiguous).

Examples :
Input: [10, 9, 2, 5, 3, 7, 101, 18] → Output: 4 (e.g., [2, 3, 7, 101])
Input: [0, 1, 0, 3, 2, 3] → Output: 4 (e.g., [0, 1, 2, 3])

Solution (Dynamic Programming) :


def length_of_LIS(nums: list[int]) -> int:
dp = [1] len(nums)
for i in range(1, len(nums)):
for j in range(i):
if nums[i] > nums[j]:
dp[i] = max(dp[i], dp[j] + 1)
return max(dp) if dp else 0

Test Cases
print(length_of_LIS([10, 9, 2, 5, 3, 7, 101, 18])) # 4
print(length_of_LIS([0, 1, 0, 3, 2, 3])) # 4

Optimized Solution (Binary Search - O(n log n)) :


import bisect

def length_of_LIS(nums: list[int]) -> int:


tails = []
for num in nums:
idx = bisect.bisect_left(tails, num)
if idx == len(tails):
tails.append(num)
else:
tails[idx] = num
return len(tails)

Evaluation Points :
•⁠ ⁠DP solution (O(n²)) is acceptable for interviews.
•⁠ ⁠Bonus: Binary search optimization (O(n log n)) for advanced candidates.

Live Coding Tips : Ask, “Can you reconstruct the subsequence?” (Track predecessors in DP array).

You might also like