Bird
Raised Fist0
LLDsystem_design~20 mins

Composite pattern in LLD - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Composite Pattern Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
1:30remaining
Understanding the Composite Pattern Structure
In the Composite pattern, which component is responsible for defining the interface for all objects in the composition, including both simple and complex elements?
ALeaf component
BComposite component
CComponent interface
DClient component
Attempts:
2 left
💡 Hint
Think about which part defines the common operations for all objects.
❓ Architecture
intermediate
2:00remaining
Composite Pattern Request Flow
Consider a file system modeled using the Composite pattern where folders are composites and files are leaves. When a client calls the 'getSize()' method on a folder, what is the correct flow of requests?
AThe folder sums sizes by calling getSize() on each child, which may be files or folders recursively.
BThe folder returns a fixed size without checking children.
CThe folder calls getSize() only on files directly inside it, ignoring subfolders.
DThe folder delegates getSize() calls to the client to handle.
Attempts:
2 left
💡 Hint
Think about how composite objects handle operations on their children.
❓ scaling
advanced
2:30remaining
Scaling Composite Pattern for Large Hierarchies
When using the Composite pattern to model a large organizational chart with thousands of employees and departments, which approach best improves performance when calculating total salaries?
ACache the total salary at each composite node and update caches on changes.
BRecalculate total salary from scratch on every request.
CUse a separate flat list of employees and ignore the composite structure.
DLimit the depth of the hierarchy to reduce recursion.
Attempts:
2 left
💡 Hint
Think about avoiding repeated expensive calculations.
❓ tradeoff
advanced
2:00remaining
Tradeoffs in Composite Pattern Design
What is a common tradeoff when using the Composite pattern to unify individual objects and compositions in a system?
AIt eliminates the need for interfaces but complicates inheritance.
BIt improves performance but increases memory usage drastically.
CIt reduces code reuse but makes debugging easier.
DIt simplifies client code but can make the design more complex and harder to restrict types.
Attempts:
2 left
💡 Hint
Consider how uniformity affects design flexibility and complexity.
❓ component
expert
3:00remaining
Identifying Component Responsibilities in Composite Pattern
In a GUI framework using the Composite pattern, which component should handle the 'draw()' operation to correctly render both simple widgets and containers with children?
AOnly the Composite components implement draw(), leaves do not implement draw().
BLeaf components implement draw() to render themselves; Composite components implement draw() by calling draw() on children.
CThe client calls draw() directly on each leaf, skipping composites.
DA separate renderer class handles draw() for all components.
Attempts:
2 left
💡 Hint
Think about how each component type contributes to rendering.

Practice

(1/5)
1. What is the main purpose of the Composite pattern in system design?
easy
A. To create a single instance of a class
B. To separate interface from implementation
C. To provide a way to access elements of a collection sequentially
D. To treat individual objects and compositions of objects uniformly

Solution

  1. Step 1: Understand the Composite pattern goal

    The Composite pattern allows treating individual objects and groups of objects the same way.
  2. Step 2: Compare with other design patterns

    Other options describe different patterns: Singleton (A), Iterator (D), Bridge (B).
  3. Final Answer:

    To treat individual objects and compositions of objects uniformly -> Option D
  4. Quick Check:

    Composite pattern = treat objects uniformly [OK]
Hint: Composite = treat single and group objects the same [OK]
Common Mistakes:
  • Confusing Composite with Singleton pattern
  • Thinking Composite only manages single objects
  • Mixing Composite with Iterator or Bridge patterns
2. Which of the following is the correct way to declare a composite interface method in a class diagram for the Composite pattern?
easy
A. int calculateSum(int a, int b);
B. void add(Component component);
C. String toString();
D. boolean equals(Object obj);

Solution

  1. Step 1: Identify typical Composite interface methods

    Composite pattern usually includes methods like add(), remove(), and getChild() to manage children.
  2. Step 2: Match method signature to Composite pattern

    Only void add(Component component); fits the pattern's purpose of managing child components.
  3. Final Answer:

    void add(Component component); -> Option B
  4. Quick Check:

    Composite interface method = add(Component) [OK]
Hint: Composite interface manages children with add/remove methods [OK]
Common Mistakes:
  • Choosing unrelated method signatures
  • Confusing standard Object methods with Composite methods
  • Ignoring the need to manage child components
3. Given the following code snippet in a Composite pattern implementation, what will be the output?
class Component:
  def operation(self):
    pass

class Leaf(Component):
  def operation(self):
    return "Leaf"

class Composite(Component):
  def __init__(self):
    self.children = []
  def add(self, component):
    self.children.append(component)
  def operation(self):
    results = []
    for child in self.children:
      results.append(child.operation())
    return "Composite(" + ", ".join(results) + ")"

leaf1 = Leaf()
leaf2 = Leaf()
composite = Composite()
composite.add(leaf1)
composite.add(leaf2)
print(composite.operation())
medium
A. Composite(Leaf, Leaf)
B. Leaf, Leaf
C. Composite()
D. Leaf

Solution

  1. Step 1: Understand Leaf operation output

    Each Leaf's operation returns the string "Leaf".
  2. Step 2: Understand Composite operation output

    Composite calls operation on each child and joins results with commas inside "Composite(...)".
  3. Final Answer:

    Composite(Leaf, Leaf) -> Option A
  4. Quick Check:

    Composite operation = Composite(Leaf, Leaf) [OK]
Hint: Composite operation joins child operations in parentheses [OK]
Common Mistakes:
  • Expecting just 'Leaf' output
  • Ignoring the Composite wrapper in output
  • Confusing list join syntax
4. In the following Composite pattern code, what is the main error?
class Component:
  def operation(self):
    pass

class Leaf(Component):
  def operation(self):
    return "Leaf"

class Composite(Component):
  def __init__(self):
    self.children = []
  def add(self, component):
    self.children.append(component)
  def operation(self):
    results = []
    for child in self.children:
      child.operation()
    return "Composite(" + ", ".join(results) + ")"
medium
A. The add method does not check component type
B. The Composite class does not initialize children list
C. The operation method does not collect child results
D. The Leaf class does not inherit from Component

Solution

  1. Step 1: Analyze operation method in Composite

    The loop calls child.operation() but does not append results to the list.
  2. Step 2: Identify missing result collection

    Without appending, results remains empty, causing incorrect output.
  3. Final Answer:

    The operation method does not collect child results -> Option C
  4. Quick Check:

    Missing append in loop = operation method error [OK]
Hint: Check if child results are collected in operation method [OK]
Common Mistakes:
  • Ignoring missing append to results list
  • Thinking add method type check is mandatory
  • Assuming inheritance error without evidence
5. You are designing a UI framework using the Composite pattern. You want to add a feature to calculate the total number of visible elements in a nested component tree. Which approach best fits the Composite pattern principles?
hard
A. Add a countVisible() method to the Component interface, implemented by Leaf and Composite classes
B. Use a global counter variable updated externally during rendering
C. Only count visible elements in Leaf nodes, ignoring Composite nodes
D. Traverse the tree manually outside the classes to count visible elements

Solution

  1. Step 1: Apply Composite pattern principle of uniformity

    Adding countVisible() to Component interface lets all nodes handle counting uniformly.
  2. Step 2: Implement counting in Leaf and Composite

    Leaf returns 1 if visible, 0 otherwise; Composite sums counts from children.
  3. Final Answer:

    Add a countVisible() method to the Component interface, implemented by Leaf and Composite classes -> Option A
  4. Quick Check:

    Uniform method in Component = best Composite design [OK]
Hint: Add counting method to Component interface for uniformity [OK]
Common Mistakes:
  • Using external counters breaking encapsulation
  • Counting only leaves ignoring composites
  • Manual traversal outside object methods
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard