Minimum Cost to Theme Feed Rows With No Adjacent Repeats

Last updated: November 29, 2026

Quick Overview

A feed has n rows and k visual themes; cost[i][j] is the cost of rendering row i with theme j. Choose a theme per row so that no two adjacent rows share a theme and the total cost is minimum. Solve it in O(nk) time.

LinkedIn
Coding & Algorithms
Software Engineer
LinkedIn
November 29, 2026
Software Engineer
Technical Screen
Coding & Algorithms
Medium

0

0

0 solved


A feed has n rows and k visual themes; cost[i][j] is the cost of rendering row i with theme j. Choose a theme per row so that no two adjacent rows share a theme and the total cost is minimum. Solve it in O(nk) time.

A LinkedIn flavored version of the classic adjacent-color minimization that its screens are known for. The interviewer first accepts O(nk^2), then pushes for the O(nk) trick of tracking the best and second-best previous values.

What the Interviewer Expects
  • Defines dp[i][j] as min cost through row i with row i using theme j
  • Writes the O(nk^2) recurrence first
  • Optimizes to O(nk) by keeping the smallest and second smallest of the previous row
  • Uses O(k) or O(1) extra space
  • Handles k = 1 with more than one row as infeasible
Key Topics to Cover
dynamic programming
space optimization
min and second min
state compression
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • How would you reconstruct the chosen themes?
  • What if the rule is no repeats within any window of 3 rows?
  • What changes if some themes are disallowed for certain row types, like ads?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements

cost is n by k with nonnegative values. Adjacent rows must differ. Return the minimum total, 0 for no rows, and -1 (or raise) if k = 1 and n > 1 since that is impossible....

High-Level Design

Recurrence: dp[i][j] = cost[i][j] + min(dp[i-1][m] for m != j). The inner min over all m except j is the previous row's minimum, unless j is the argmin, in which case it is the second minimum. So pe...


Submit Your Answer
Markdown supported