TCS AI Career — Exam Prep Guide

110 Questions · Click any card to reveal the answer · Track your progress below

§1 JavaScript Fundamentals Q1–Q10
Q1 Explain the difference between var, let, and const with examples. Easy
var is function-scoped, hoisted and initialized to undefined, can be reassigned and redeclared, creates global properties. let is block-scoped, hoisted but in TDZ (Temporal Dead Zone), can be reassigned but not redeclared. const is block-scoped, hoisted but in TDZ, cannot be reassigned or redeclared (but objects/arrays it references CAN be mutated).
var x = 1; var x = 2; // OK let a = 1; let a = 2; // SyntaxError! const c = 1; c = 2; // TypeError! const d = [1,2]; d.push(3); // OK — mutating the array // var leaks outside blocks: var y = 10 inside block; console.log(y); // 10 // let does NOT leak: let b = 20 inside block; console.log(b); // ReferenceError
Key insight: var is function-scoped (leaks out of blocks), let and const are block-scoped. Always use const by default.
Q2 What is hoisting in JavaScript? How does it differ for var, let, and const? Medium
Hoisting is JavaScript's behavior of moving declarations to the top of their scope during compilation. var declarations are hoisted and initialized to undefined. let and const are hoisted but NOT initialized — they sit in a Temporal Dead Zone (TDZ) from the start of the block until the declaration line. Accessing them before declaration throws ReferenceError. Function declarations are fully hoisted (name + body). Function expressions are NOT.
console.log(a); // undefined (hoisted + initialized) var a = 10; console.log(b); // ReferenceError (TDZ) let b = 20; greet(); // Works! declaration fully hoisted function greet() { console.log("Hi"); }
Q3 What is a closure? Give one practical use case. Medium
A closure is a function that "remembers" the variables from its outer scope even after the outer function has finished executing. The inner function has access to the outer function's variables via the scope chain.
function createCounter() { let count = 0; return { increment: () => ++count, getCount: () => count }; } const counter = createCounter(); counter.increment(); counter.increment(); console.log(counter.getCount()); // 2
Practical use cases: Data privacy/encapsulation, event handlers/callbacks, partial application/currying, memoization.
Q4 What is the difference between == and ===? Easy
== (abstract equality) compares values after type coercion — JS converts operands to the same type. === (strict equality) compares both value and type — no coercion. 5 == "5"true (string coerced to number) 5 === "5"false (different types) null == undefinedtrue null === undefinedfalse Always use === to avoid subtle bugs.
Q5 What is the difference between null and undefined? Easy
undefined means "a variable has been declared but has no value assigned yet" — it's the default for uninitialized variables, missing arguments, missing properties. null means "intentionally no value" — you assign it explicitly to indicate emptiness. typeof undefined === "undefined" but typeof null === "object" (a well-known JS bug).
Q6 Explain this in: a regular function, an arrow function, and a method. Medium
Regular function: this depends on HOW it's called (dynamic binding). Called globally → global object (undefined in strict mode). Method: this = the object before the dot (the caller). Arrow function: this = the enclosing scope where it was DEFINED (lexical/static binding) — cannot be changed with call/apply/bind.
const obj = { name: "TCS", getName: function() { console.log(this.name); }, getNameArrow: () => { console.log(this.name); } }; obj.getName(); // "TCS" — this = obj obj.getNameArrow(); // undefined — this = global
Q7 What is the difference between an arrow function and a normal function? List at least 3 differences. Medium
1. this binding: Arrow functions don't have their own this; they inherit from enclosing scope. Regular functions get their own this based on how they're called. 2. arguments object: Arrow functions don't have an arguments object — use rest parameters (...args) instead. Regular functions have arguments. 3. Constructor: Arrow functions CANNOT be used with new. They have no prototype and throw errors as constructors. 4. Syntax: Arrow functions have shorter syntax with implicit return. 5. call/apply/bind: These have no effect on this in arrow functions.
Q8 What is event bubbling and event capturing in the browser? Medium
When an event occurs, it travels through the DOM in three phases: (1) Capturing (top-down): window → document → html → body → parent → target. (2) Target: event reaches the target element. (3) Bubbling (bottom-up): target → parent → body → html → document → window. addEventListener's third parameter controls which phase: false (default) = bubbling, true = capturing. event.stopPropagation() stops the event from continuing.
Q9 What is the difference between call, apply, and bind? Give one example each. Medium
All control what this refers to. call: invokes immediately, arguments passed individually. apply: invokes immediately, arguments passed as an array. bind: does NOT invoke immediately, returns a NEW function with this permanently bound.
function greet(greeting, punctuation) { console.log(`${greeting}, ${this.name}${punctuation}`); } const user = { name: "Alice" }; greet.call(user, "Hello", "!"); // "Hello, Alice!" greet.apply(user, ["Hi", "..."]); // "Hi, Alice..." const bound = greet.bind(user, "Hey"); bound("?!"); // "Hey, Alice?!"
Q10 What are higher-order functions? Give 3 examples from Array methods. Easy
A higher-order function is a function that either takes a function as an argument or returns a function. Examples: map (transforms each element), filter (keeps elements that pass a test), reduce (accumulates into a single value). Also: forEach, find, sort, every, some.
const nums = [1, 2, 3, 4, 5]; const doubled = nums.map(n => n * 2); // [2, 4, 6, 8, 10] const evens = nums.filter(n => n % 2 === 0); // [2, 4] const sum = nums.reduce((acc, n) => acc + n, 0); // 15
§1B JS — Predict the Output Q11–Q20
Q11 console.log(a); var a = 10; console.log(a); Easy
Output: undefined, then 10. var is hoisted and initialized to undefined. First log sees undefined, then a = 10 runs, second log prints 10.
Q12 console.log(b); let b = 20; Easy
Output: ReferenceError: Cannot access 'b' before initialization. let is in TDZ (Temporal Dead Zone) until the declaration line.
Q13 Closure counter: function outer() { let count = 0; return function inner() { count++; console.log(count); } } const fn = outer(); fn(); fn(); fn(); Medium
Output: 1, 2, 3. Classic closure — inner function captures count from outer's scope. count persists between calls.
Q14 obj.getName() and obj.getNameArrow() with name: "TCS" Medium
Output: TCS, then undefined. Regular function: this = obj → prints "TCS". Arrow function: this = enclosing scope (global), not obj → undefined.
Q15 setTimeout(() => console.log("A"), 0); Promise.resolve().then(() => console.log("B")); console.log("C"); Hard
Output: C, B, A. Order: Sync code first → microtasks (Promise) → macrotasks (setTimeout).
Q16 for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 0); } Medium
Output: 3, 3, 3. var is function-scoped — one shared i. By the time callbacks run, the loop is done and i = 3.
Q17 for (let i = 0; i < 3; i++) { setTimeout(() => console.log(i), 0); } Medium
Output: 0, 1, 2. let is block-scoped — each iteration creates a new i binding. Closures capture specific values.
Q18 const arr = [1,2,3]; const arr2 = arr; arr2.push(4); console.log(arr); Easy
Output: [1, 2, 3, 4]. Arrays are reference types — arr2 and arr point to the same array in memory. Pushing to arr2 modifies the shared array.
Q19 const x = {a:1}; const y = {a:1}; console.log(x === y); Easy
Output: false. Objects are compared by reference, not value. Two distinct objects in memory → different references.
Q20 const data = [1,2,3,4,5]; const result = data.filter(n => n%2===0).map(n => n*10); console.log(result); Medium
Output: [20, 40]. filter keeps evens → [2, 4], then map multiplies by 10 → [20, 40].
§2 Promises, Async/Await & Event Loop Q21–Q30
Q21 What is the event loop in Node.js? Medium
The event loop allows Node.js to perform non-blocking I/O despite being single-threaded. Call Stack executes JS code. Web/Node APIs handle async operations (via libuv). Callback Queues hold completed callbacks. Event Loop checks if call stack is empty, then picks callbacks from queues. Order: sync → microtasks → macrotasks. In simple terms: it's a while-loop that continuously checks for and executes pending callbacks.
Q22 Difference between callbacks, promises, and async/await. Medium
Callbacks: pass a function as argument, nesting leads to callback hell, no built-in error handling. Promises: object representing future value, .then()/.catch() for handling, supports chaining, avoids callback hell. Async/await: syntactic sugar over Promises, async makes function return Promise, await pauses until Promise settles, makes async code look synchronous, easier error handling with try/catch.
Q23 What is callback hell? How do promises or async/await help? Easy
Callback hell is deeply nested callbacks creating a "pyramid of doom" — hard to read, debug, and maintain. Promises flatten it with .then() chaining. Async/await makes it even cleaner with synchronous-looking code and try/catch error handling.
Q24 What is the difference between microtasks and macrotasks? Hard
Microtasks (higher priority): Promise.then/catch/finally, queueMicrotask(), MutationObserver, process.nextTick (Node). Macrotasks (lower priority): setTimeout, setInterval, setImmediate, I/O callbacks. Execution order: after each macrotask, event loop drains ALL microtasks before next macrotask. Rule: microtasks always run before macrotasks.
Q25 What is the order of execution among setTimeout, Promise.then, and process.nextTick? Hard
In Node.js: (1) process.nextTick — fastest, runs after current op, before other microtasks. (2) Promise.then / other microtasks. (3) setTimeout / setImmediate / macrotasks.
Q26 Explain Promise.all, Promise.allSettled, Promise.race, and Promise.any. Medium
Promise.all: resolves when ALL resolve, rejects if ANY rejects. Promise.allSettled: resolves when ALL settle (never rejects). Returns status + value for each. Promise.race: settles with the FIRST one to settle (resolve or reject). Promise.any: resolves with the FIRST to resolve, rejects only if ALL reject.
Q27 What happens if you don't handle a rejected promise? Easy
Unhandled promise rejection. In browsers: warning in console. In Node.js v15+: crashes the process (like uncaught exception). Before v15: just a warning. Always use .catch() or try/catch.
Q28 How do you convert a callback-based function to a promise-based one? Medium
(1) Wrap in new Promise:
return new Promise((resolve, reject) => { callback((err, data) => { if (err) reject(err); else resolve(data); }); });
(2) Use util.promisify (Node.js). (3) Use built-in promise versions (e.g., fs.promises).
Q29 What is the purpose of async before a function? What does it return? Easy
async makes a function treatable as asynchronous and allows using await inside. It always returns a Promise. If you return a non-Promise value, it's automatically wrapped in Promise.resolve(). If it throws, the promise rejects with that error.
Q30 How do you handle errors in async/await code? Easy
Use try/catch. Async functions that throw cause the returned promise to reject. Without try/catch, leads to unhandled rejection. Also can use .catch() per-await: await fn().catch(err => default). Always handle errors.
§2B Async — Predict the Output Q31–Q35
Q31 console.log("1"); setTimeout(() => console.log("2"), 0); Promise.resolve().then(() => console.log("3")); console.log("4"); Hard
Output: 1, 4, 3, 2. Sync first → microtask (Promise) → macrotask (setTimeout).
Q32 async function test() with console.log("A"), await, console.log("C"). Called after console.log("X") and before console.log("Y"). Hard
Output: X, A, Y, C. "X" sync, "A" sync inside test until await, "Y" sync (test paused), "C" after await resolves.
Q33 Promise chain with .then("A").then("B"), setTimeout("C", 0), console.log("D"). Hard
Output: D, A, B, C. Sync first → all microtasks (chained .thens) → macrotask.
Q34 async function f1() { throw new Error("Oops"); } f1().catch(...); console.log("Done"); Hard
Output: Done, Caught: Oops. f1 returns a rejected promise. .catch() is async. "Done" runs first (sync), then catch.
Q35 Promise chain returning Promise.reject("Err"), with .catch("B"), console.log("C"). Hard
Output: C, A, B Err. "C" sync, "A" microtask, "B" catches the rejected promise from .then().
§3 Node.js Core Q36–Q50
Q36 Why is Node.js "single-threaded" but handles many concurrent requests? Medium
JS code runs on a single thread (call stack). But libuv offloads I/O to a thread pool (4 threads) or OS event notification. Event loop picks up callbacks when async ops complete. Non-blocking I/O doesn't block the main thread. Analogy: one chef delegating to assistants, checking back when done.
Q37 What is the role of libuv in Node.js? Medium
libuv is a cross-platform C library that provides async I/O. • Implements the event loop (timers, poll, check phases). • Thread pool (~4 threads) for file system, DNS. • Async networking (epoll/kqueue/IOCP). • Child processes, pipes, signal handling. It's the engine behind Node.js's non-blocking I/O.
Q38 Difference between CommonJS and ES modules. Medium
CommonJS: require() syntax, synchronous loading, module.exports, no tree shaking. ES Modules: import/export syntax, asynchronous compile-time loading, supports tree shaking, top-level await. CommonJS uses .js default, ES modules use .mjs or "type":"module" in package.json.
Q39 What is the purpose of module.exports vs exports? Easy
module.exports is the actual exported object. exports is a shorthand alias initially pointing to the same object. Use module.exports for default export, exports.name for named exports. Never reassign exports directly (breaks the link).
Q40 Main modules: fs, http, path, os. Easy
fs: file system operations (read, write, delete). http: create servers and make requests. path: handle file paths cross-platform (join, resolve, extname). os: system info (cpus, freemem, hostname).
Q41 fs.readFile vs fs.readFileSync? When to avoid sync? Easy
readFile is async (non-blocking, callback/promise). readFileSync is sync (blocks the event loop). Avoid sync in web servers/APIs — blocks ALL other requests. Sync is fine for scripts, CLI tools, startup init.
Q42 What is a stream? What are the types? Medium
A stream handles data piece by piece (not all at once). Four types: Readable (source — fs.createReadStream, stdin). Writable (destination — fs.createWriteStream, stdout). Duplex (both — net.Socket). Transform (modifies data — zlib.createGzip). Use .pipe() or .pipeline() for automatic backpressure handling.
Q43 What is backpressure in streams? Hard
Backpressure occurs when readable produces data faster than writable can consume. Buffer fills up. Fix: use stream.pipe() (auto-handles), stream.pipeline() (safer), or manually: check write() return value (false when full), listen for 'drain' event.
Q44 What is EventEmitter? Easy
Core Node.js class implementing the pub/sub pattern. Methods: on()/addListener() — register, emit() — fire, once() — fires once then removed, removeListener(). Extended by streams, HTTP servers, process, and custom services.
Q45 process.nextTick vs setImmediate? Hard
process.nextTick: runs immediately after current operation, before any other async (even microtasks). setImmediate: runs in "check" phase of next event loop iteration, after I/O callbacks (macrotask). Priority: sync → nextTick → Promise.then → setImmediate. Use nextTick for ASAP operations; setImmediate for after I/O.
Q46 Purpose of package.json? Name 4 important fields. Easy
Manifest file for a Node.js project. Important fields: name, version, scripts, dependencies, devDependencies, main, type, engines.
Q47 dependencies vs devDependencies? Easy
dependencies: needed for production (e.g., express, mongoose). devDependencies: needed only for development/testing (e.g., jest, nodemon, eslint). Production install (npm install --production) skips devDependencies.
Q48 What is package-lock.json? Easy
Records exact versions of every package and sub-dependency. Ensures reproducibility across environments. Prevents "works on my machine" issues. Always commit it. Never commit node_modules.
Q49 How to read environment variables? Easy
process.env global object. Use the dotenv package: require("dotenv").config() reads a .env file. Access via process.env.VAR_NAME. Values are always strings. Add .env to .gitignore.
Q50 Common memory leaks in Node.js? Hard
• Unclosed event listeners (adding in loop without removing). • Closures holding large objects. • Global variables. • Unclosed streams. • Cache without eviction. • Timers not cleared. • Circular references (rare with modern V8). Detect with: process.memoryUsage(), Chrome DevTools, --inspect flag.
§3B Node.js Coding Q51–Q55
Q51 Write an HTTP server returning "Hello TCS" for / and 404 for others. Medium
const http = require("http"); const server = http.createServer((req, res) => { if (req.url === "/" && req.method === "GET") { res.writeHead(200, { "Content-Type": "text/plain" }); res.end("Hello TCS"); } else { res.writeHead(404, { "Content-Type": "text/plain" }); res.end("404 Not Found"); } }); server.listen(3000, () => console.log("Server running on port 3000"));
Q52 Read data.txt asynchronously with error handling. Medium
const fs = require("fs").promises; async function readFile() { try { const data = await fs.readFile("data.txt", "utf-8"); console.log(data); } catch (err) { console.error("Error:", err.message); } } readFile();
Q53 EventEmitter emitting dataReady with {id: 1}. Medium
const { EventEmitter } = require("events"); const emitter = new EventEmitter(); emitter.on("dataReady", (payload) => console.log("Data ready:", payload) ); emitter.emit("dataReady", { id: 1 });
Q54 Fix the synchronous file read in an Express route. Medium
Problem: fs.readFileSync blocks ALL other requests. Fix: use async fs.promises.readFile or streams.
app.get("/file", async (req, res) => { try { const content = await fs.promises.readFile("data.txt", "utf-8"); res.send(content); } catch (err) { res.status(500).send("Error reading file"); } });
Q55 Fetch multiple URLs with Promise.all. Medium
async function fetchAll(urls) { const promises = urls.map(url => fetch(url).then(res => { if (!res.ok) throw new Error(`${url} failed`); return res.json(); }) ); return Promise.all(promises); } const [users, posts] = await fetchAll(["/api/users", "/api/posts"]);
§4 Express & REST Q56–Q70
Q56 What is Express.js? Why use it over the http module? Easy
Minimal, flexible Node.js web framework. Over raw http: built-in routing (params, query, methods), middleware pipeline (body parsing, auth, logging), built-in helpers (res.json, res.status), centralized error handling, huge ecosystem.
Q57 What is middleware in Express? Medium
A function with (req, res, next) signature. Can execute code, modify req/res, end the cycle, or call next(). A route handler is middleware that ends the response (no next()). Global middleware runs for all routes; route-specific runs only for that route.
Q58 What is the order of execution of multiple middlewares? Medium
Executes in definition order (top to bottom). Each must call next() to continue. If it sends a response, the pipeline stops. Global app.use() runs for ALL routes. Error middleware (4 params) must be defined LAST.
Q59 express.json() and express.urlencoded()? Easy
Built-in middleware that parse request bodies. express.json(): parses JSON payloads (application/json). express.urlencoded(): parses form data (application/x-www-form-urlencoded). Without these, req.body is undefined. Most common beginner mistake!
Q60 app.use() vs app.get()? Easy
app.use(): middleware for ALL HTTP methods at a path. app.get(): handler for GET requests only. Also: app.post(), app.put(), app.delete().
Q61 What is a router in Express? Easy
A mini Express app handling routes for specific resources. Organizes routes into separate files. router.get(), router.post() — then mount with app.use("/users", router). Benefits: separation of concerns, avoids massive app.js, routes can have own middleware.
Q62 PUT vs PATCH? Easy
PUT replaces the ENTIRE resource (must send complete object). PATCH partially updates (only send changed fields).
Q63 Common HTTP status codes. Easy
200 OK   201 Created   400 Bad Request (client sent invalid data)   401 Unauthorized (no/invalid token)   403 Forbidden (authenticated but no permission)   404 Not Found   500 Internal Server Error. 4xx = client fault, 5xx = server fault.
Q64 How to handle errors in async Express handlers? Medium
Use try/catch or an asyncHandler wrapper. Async throws won't auto-trigger Express error handler.
const asyncHandler = (fn) => (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next); app.get("/data", asyncHandler(async (req, res) => { const data = await fetchData(); res.json(data); }));
Error middleware must have 4 params: (err, req, res, next).
Q65 What is CORS? How do you enable it in Express? Easy
CORS (Cross-Origin Resource Sharing) — browser security restricting cross-origin requests. Use the cors package: app.use(cors()). For specific origin: app.use(cors({ origin: "http://localhost:3000" })).
Q66 What is JWT? Medium
JSON Web Token — compact, URL-safe token for stateless auth. Has header (alg, type), payload (claims), and signature. Used for: API auth, session management, microservice auth, SSO. Sign with jwt.sign(), verify with jwt.verify().
Q67 How to secure routes with auth middleware? Medium
Check Authorization header → extract token → verify with jwt.verify() → attach decoded user to req.user → call next(). For roles: create a roleCheck middleware checking req.user.role.
Q68 res.send() vs res.json() vs res.sendFile()? Easy
res.send(): auto-detects content type, can send strings/buffers/objects. res.json(): sets Content-Type: application/json, converts to JSON. res.sendFile(): sends a file with appropriate headers.
Q69 How to access route params, query params, and request body? Easy
Route params: req.params.id (from /users/:id). Query params: req.query.role (from ?role=admin). Request body: req.body (POST, needs express.json() middleware). Query params are always strings.
Q70 What is the purpose of dotenv? Easy
Loads .env file variables into process.env. Keeps secrets out of code. Add .env to .gitignore. Create .env.example for team reference.
§4B Express Coding Q71–Q75
Q71 Minimal Express app with GET /health. Medium
const express = require("express"); const app = express(); app.get("/health", (req, res) => res.json({ status: "ok" }) ); app.listen(4000, () => console.log("Running on port 4000") );
Q72 Write a logger middleware. Medium
function logger(req, res, next) { console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`); next(); } app.use(logger);
Q73 Write a POST /users route with validation. Medium
app.use(express.json()); app.post("/users", (req, res) => { const { name, email } = req.body; if (!name || !email) return res.status(400).json({ error: "Name and email required" }); const user = { id: users.length + 1, name, email }; users.push(user); res.status(201).json(user); });
Q74 Write an error-handling middleware. Medium
app.use((err, req, res, next) => { console.error(err.stack); res.status(err.status || 500).json({ error: err.message || "Internal Server Error" }); });
Q75 Fix an async route without error handling. Medium
Problem: If fetchData() throws, Express won't catch it. Fix: wrap in try/catch or asyncHandler.
// ❌ Bad: app.get("/data", async (req, res) => { const data = await fetchData(); // may throw — NOT caught! res.json(data); }); // ✅ Good: app.get("/data", async (req, res) => { try { const data = await fetchData(); res.json(data); } catch (err) { res.status(500).json({ error: err.message }); } });
§5 Database Basics Q76–Q85
Q76 SQL vs NoSQL? Easy
SQL (MySQL, PostgreSQL): structured tables with rows/columns, fixed schema, ACID transactions, JOIN queries. NoSQL (MongoDB, Redis): flexible documents/key-value/columnar, dynamic schema, horizontal scaling, eventual consistency. SQL for complex queries/transactions. NoSQL for flexibility/scale.
Q77 What is a primary key? Easy
A column (or set of columns) that uniquely identifies each row in a table. Must be unique and not null. Examples: user_id, email (if unique). Auto-incrementing integers are common.
Q78 What is an index in a database? Easy
A data structure that speeds up data retrieval. Like a book index — instead of scanning every page, you jump to the right location. Trade-off: faster reads but slower writes (index must be updated). Use on frequently queried columns (WHERE, JOIN, ORDER BY).
Q79 What is a JOIN? INNER JOIN vs LEFT JOIN? Medium
JOIN combines rows from two tables based on a related column. INNER JOIN: returns only matching rows in BOTH tables. LEFT JOIN: returns ALL rows from left table + matching rows from right (NULLs if no match).
SELECT * FROM orders INNER JOIN users ON orders.user_id = users.id; -- only orders with matching users SELECT * FROM orders LEFT JOIN users ON orders.user_id = users.id; -- ALL orders, even without a user
Q80 What is a document in MongoDB? Easy
A document is a JSON-like data structure (BSON) stored in a collection. It has key-value pairs. Like a row in SQL but flexible — each document can have different fields.
Q81 How do you insert a document in MongoDB? Easy
db.collection.insertOne({ name: "Alice", age: 25 }) or insertMany([...]). Documents get an auto-generated _id.
Q82 What is an ORM/ODM? Easy
ORM (Object-Relational Mapper) for SQL: maps JS objects to database tables (Sequelize, TypeORM, Prisma). ODM (Object-Document Mapper) for NoSQL: maps JS objects to documents (Mongoose for MongoDB). Let you use JS methods instead of raw queries.
Q83 What is a connection pool? Easy
A cache of database connections that are reused instead of creating new ones for each request. Reduces overhead of connecting/disconnecting. Managed by the DB driver or ORM. Important for performance in production.
Q84 What is a transaction? Easy
A group of operations treated as a single unit — ALL succeed or ALL fail. Ensures data consistency. Example: bank transfer = debit account A AND credit account B. If one fails, both are rolled back.
Q85 What is the N+1 query problem? Medium
When fetching N items, you make 1 query for the list + N individual queries for related data. Example: fetch 100 users, then fetch each user's posts = 101 queries. Fix: use JOINs, eager loading, or batch queries.
§6 Coding Problems Q86–Q95
Q86 Reverse a string. Easy
const reverse = s => s.split("").reverse().join(""); // "hello" → "olleh" // Alternative: [...s].reverse().join("") // Or using reduce: s.split("").reduce((rev, c) => c + rev, "")
Q87 Check if a string is a palindrome. Easy
const isPalindrome = s => s === s.split("").reverse().join(""); // Two-pointer approach: (const isPal = s => { let i = 0, j = s.length - 1; while (i < j) { if (s[i++] !== s[j--]) return false; } return true; })
Q88 Find the most frequent element in an array. Medium
function mostFrequent(arr) { const freq = {}; arr.forEach(n => freq[n] = (freq[n] || 0) + 1); return Object.entries(freq) .sort((a, b) => b[1] - a[1])[0][0]; } // [1,2,2,3,3,3] → "3"
Q89 Remove duplicates from an array. Easy
const unique = arr => [...new Set(arr)]; // Or: arr.filter((v, i) => arr.indexOf(v) === i)
Q90 Group an array of objects by a key. Medium
function groupByKey(arr, key) { return arr.reduce((acc, item) => { (acc[item[key]] = acc[item[key]] || []).push(item); return acc; }, {}); } // Usage: groupByKey([ {name:"A", age:20}, {name:"B", age:20}, {name:"C", age:21} ], "age"); // → { 20: [{name:"A",age:20},{name:"B",age:20}], // 21: [{name:"C",age:21}] }
Q91 Implement a debounce function. Medium
function debounce(fn, delay) { let timer; return (...args) => { clearTimeout(timer); timer = setTimeout(() => fn(...args), delay); }; } // Usage: const debounced = debounce(fetch, 300); input.oninput = debounced;
Q92 Flatten an array (1 level). Easy
const flatten = arr => arr.flat(); // Or: arr.reduce((acc, val) => acc.concat(val), []) // [1, [2,3], [4,[5]]] → [1,2,3,4,[5]] // Deep flatten: JSON.parse(JSON.stringify(arr)).flat(Infinity)
Q93 Sum of even numbers in an array. Easy
const sumEven = arr => arr.filter(n => n % 2 === 0) .reduce((a, b) => a + b, 0); // Or in one pass: arr.reduce((sum, n) => n % 2 === 0 ? sum + n : sum, 0)
Q94 Two-sum problem (find two indices that add to a target). Medium
function twoSum(arr, target) { const map = new Map(); for (let i = 0; i < arr.length; i++) { const complement = target - arr[i]; if (map.has(complement)) return [map.get(complement), i]; map.set(arr[i], i); } return null; } // twoSum([2,7,11,15], 9) → [0, 1] // Time: O(n) with hashmap
Q95 Implement a simple Promise. Easy
const delayedPromise = new Promise((resolve) => { setTimeout(() => resolve("Done"), 1000); }); delayedPromise.then(result => console.log(result) ); // "Done" after 1 second
§7 Aptitude & Reasoning Q96–Q110
Q96 Salary problem: Person spends 40% rent, 20% food, saves rest. If savings = ₹12,000, find salary. Medium
Spends 40% + 20% = 60%. Saves 40%. If savings = ₹12,000, then salary = 12,000 / 0.40 = ₹30,000.
Q97 Workers problem: 15 workers × 20 days. How many days for 10 workers? Medium
15 workers × 20 days = 300 worker-days. 10 workers = 300 / 10 = 30 days.
Q98 Discount problem: Sold at ₹1,200 after 20% discount. Find the marked price. Medium
1,200 = 80% of MP → MP = 1,200 / 0.80 = ₹1,500.
Q99 Train speed: 120 km in 2 hours. Find speed in m/s. Medium
120 km / 2 h = 60 km/h = 60 × (1000/3600) = 16.67 m/s.
Q100 Simple interest: P = ₹10,000, R = 8%, T = 3 years. Find SI. Medium
SI = P × R × T / 100 = 10,000 × 8 × 3 / 100 = ₹2,400.
Q101 Number series: 2, 6, 12, 20, 30, ? Medium
Differences: 4, 6, 8, 10, 12. Pattern: n(n+1) where n = 1, 2, 3, ... Answer: 30 + 12 = 42.
Q102 Code language: CAT → FDW. How is DOG written? Medium
Pattern: each letter +3. C(+3)=F, A(+3)=D, T(+3)=W. D(+3)=G, O(+3)=R, G(+3)=J. Answer: GRJ.
Q103 A is B's brother, B is C's sister. How is A related to C? Easy
B is female (sister). A is B's brother. So A is C's brother.
Q104 Ravi is 12th from left, 15th from right. Total people? Easy
12 + 15 − 1 = 26. (Subtract 1 because Ravi is counted twice.)
Q105 Syllogism: All engineers are smart, some smart are creative. What must be true? Medium
Only "Some engineers may be creative" must be true. Not all engineers are creative, and not all smart are engineers. Some smart people being creative is given.
Q106 Verbal ability: Subject-verb agreement and tense consistency — practice area. Easy
Focus areas for TCS NQT verbal ability: • Subject-verb agreement: singular subjects take singular verbs, plural subjects take plural verbs. • Tense consistency: keep the same tense throughout a sentence or paragraph. • Article usage: a/an/the — use "a" before consonant sounds, "an" before vowel sounds, "the" for specific nouns. • Preposition errors: common confusions like "between/among", "accept/except". • Pronoun references: ensure pronouns clearly refer to the correct noun. Practice with TCS NQT verbal ability sets regularly.
Q107 Verbal ability: Error spotting — practice area. Easy
Error spotting strategy: 1. Read the entire sentence first. 2. Check subject-verb agreement. 3. Check tense consistency. 4. Check preposition usage. 5. Check article usage (a/an/the). 6. Check pronoun-antecedent agreement. 7. Check for parallel structure. Common errors: "each of the students have" → should be "has". "Between you and I" → should be "me".
Q108 Verbal ability: Sentence improvement — practice area. Easy
Sentence improvement strategy: • Look for grammatical errors first, then word choice. • Check if the improved sentence maintains the original meaning. • Pay attention to: - Active vs passive voice - Word order - Redundancy - Idiomatic expressions Example: "He did a mistake" → "He made a mistake" (correct collocation).
Q109 Verbal ability: Reading comprehension — practice area. Easy
Reading comprehension tips: 1. Read the passage carefully (once is enough if you're careful). 2. Underline key points while reading. 3. Go to the questions — identify keywords. 4. Go back to the passage to find the answer. 5. Eliminate obviously wrong options. 6. Watch for: synonyms/paraphrasing in answers, absolute words ("always", "never" are usually wrong), inference vs explicit statement. Time management: spend ~2 minutes per passage+questions.
Q110 Verbal ability: General tips for TCS NQT verbal section. Easy
TCS NQT Verbal Ability Tips:Time: ~18 minutes for ~20 questions — ~50 seconds each. • Synonyms/Antonyms: build vocabulary, read regularly. • Sentence completion: look for context clues, collocations. • Error spotting: grammar rules — subject-verb, tense, articles, prepositions. • Sentence improvement: find the grammatically correct alternative. • Reading comprehension: practice skimming and scanning. • Common topics: technology, environment, business, science. Practice sources: IndiaBix, Prepinsta, TCS-specific mock tests, previous year papers.
Progress: 0 / 110 revealed