Implementation of deepFlattenAndGroupByTypeWithFrequency

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2025-06-11

Problem Statement

Design and implement a utility function deepFlattenAndGroupByTypeWithFrequency that takes an arbitrarily nested data structure (e.g., list/array containing mixed data types like numbers, strings, booleans, objects, etc.) and performs the following operations:


1.Deep Flattening
•Traverse the entire nested structure recursively.
•Extract all leaf-level elements into a flat sequence.
2.Grouping by Type
•Group elements by their data type (number, string, boolean, object, etc.).
•Custom type resolution (e.g., arrays → list, dicts → map in Python/Java).
3.Frequency Counting
•For each group, count the frequency of each unique element.
4.Return Structure
•The function should return a nested map/dictionary-like structure:
1 2{ 3"number": { 1: 2, 5: 1, 10: 3 }, 4"string": { "a": 2, "b": 1 }, 5"boolean": { true: 3, false: 1 } 6}


Functional Requirements (FR)


•Accept arbitrarily nested lists/arrays/objects as input.
•Flatten deeply without losing values.
•Correctly identify and classify data types.
•Maintain frequency count per type group.
•Provide results in a consistent, deterministic structure.


Non-Functional Requirements (NFR)


•Efficiency – Handle very large nested structures without excessive recursion depth.
•Extensibility – Easy to support new/custom types.
•Deterministic Output – Same input always yields same grouping and ordering.
•Thread-Safety (optional) – Ensure correctness in multi-threaded use cases.


Core Entities / Classes


Class / Module Responsibilities

DeepFlattener Recursively traverse nested structures and extract leaf elements.

TypeClassifier Identify and classify element type into a predefined category.

FrequencyCounter Count frequency of elements within each type group.

Aggregator Combine results into final grouped output format.

DeepFlattenAndGroupByTypeWithFrequency (Facade) Orchestrator that invokes all modules to produce the final result.


Example Input / Output


Input:

1 2[1, "a", [2, "b", [1, "a", true]], false, 2, 1]


Output:

1 2{ 3"number": { "1": 3, "2": 2 }, 4"string": { "a": 2, "b": 1 }, 5"boolean": { "true": 1, "false": 1 } 6}


Design Considerations


1.Recursion vs Iterative Traversal
•Use recursion with stack depth checks, or iterative DFS with an explicit stack.
2.HashMaps for Frequency Counting
•Each type group maintains its own frequency map.
3.Extensibility
•Easily support JSON-like objects, custom enums, or user-defined types.
4.Error Handling
•Handle null/undefined gracefully.
•Ignore unsupported types or classify them under "unknown".


✅ This problem statement tests:


•Recursive traversal & flattening logic.
•Type classification and grouping.
•Frequency counting using hash maps.
•Object-oriented modular design of a utility library.


Solution

Comments