Given a deeply nested JSON object representing a company’s departments, teams, and employees, write a function to flatten it into an array of employee records with department and team info attached.
💡 Model Answer
You can solve this by iterating through each department, then each team, and pushing a new record for every employee. In TypeScript you might write:
interface Employee { id: number; name: string; role: string; }
interface Team { teamName: string; members: Employee[]; }
interface Department { deptName: string; teams: Team[]; }
interface FlatEmployee extends Employee { deptName: string; teamName: string; }
function flattenCompany(data: Department[]): FlatEmployee[] {
const result: FlatEmployee[] = [];
for (const dept of data) {
for (const team of dept.teams) {
for (const emp of team.members) {
result.push({ ...emp, deptName: dept.deptName, teamName: team.teamName });
}
}}
return result;
}
This runs in O(n) time where n is the total number of employees, and uses O(n) space for the output array. If you prefer a functional style, you can use flatMap or reduce, but the nested loops are clear and efficient.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.
Get Assisting AI — Starts at ₹500