QA / SDET interview questions & answers

20 QA / SDET interview questions with complete model answers, spanning System design, Technical, Coding, Product & growth. The bank holds 47 QA / SDET questions in total, tagged by round and difficulty.

CodingEasyQA / SDET

1. Write a program to open a web page.

Model answer

const { chromium } = require('playwright');

async function openWebPage(url) {
  const browser = await chromium.launch({ headless: false });

  try {
    const page = await browser.newPage();
    await page.goto(url, { waitUntil: 'domcontentloaded' });
    console.log(`Opened: ${page.url()}`);
    console.log(`Title: ${await page.title()}`);

    // Keep the browser open until the user closes it.
    await page.waitForEvent('close');
  } finally {
    await browser.close();
  }
}

const url = process.argv[2] || 'https://www.makemytrip.com/';
openWebPage(url).catch((error) => {
  console.error('Could not open the page:', error.message);
  process.exitCode = 1;
});
  • Install the dependency with npm install playwright and install its browser with npx playwright install chromium.
  • Run with node open-page.js https://example.com; the MakeMyTrip homepage is the default.

Complexity: O(1) application memory, excluding the browser’s own resource use.

CodingEasyQA / SDET

2. Can you write WebDriver drv = new WebDriver();?

Model answer

No. In Selenium’s Java API, WebDriver is an interface, so it cannot be instantiated with new WebDriver(); Java will reject that statement. Instantiate a concrete implementation and assign it to the interface type, for example: WebDriver drv = new FirefoxDriver();.

The JavaScript below illustrates the same idea: create a concrete driver implementation and use it through a shared contract.

// Java equivalent: WebDriver drv = new FirefoxDriver();
class FirefoxDriver {
  get(url) {
    console.log(`Navigating to ${url} with Firefox`);
  }
}

function createDriver(DriverImplementation) {
  return new DriverImplementation();
}

const drv = createDriver(FirefoxDriver);
drv.get("https://www.makemytrip.com");
  • WebDriver provides the contract; FirefoxDriver supplies the implementation.
  • In Java, instantiate the concrete driver, not the interface.
  • Complexity: O(1) time and O(1) space for this illustrative object creation.
CodingEasyQA / SDET

3. Given an array containing the numbers 1 through 100 with one number missing, how would you find the missing number?

Model answer

function findMissingNumber(numbers) {
  const expectedCount = 100;
  const expectedSum = (expectedCount * (expectedCount + 1)) / 2;
  const actualSum = numbers.reduce((sum, value) => sum + value, 0);

  return expectedSum - actualSum;
}

// Example: 42 is missing from the input.
const numbers = Array.from({ length: 100 }, (_, index) => index + 1)
  .filter((value) => value !== 42);

console.log(findMissingNumber(numbers)); // 42
  • The sum of integers from 1 through 100 is 100 * 101 / 2; subtract the array sum to get the missing value.
  • This assumes the array contains distinct values from 1 through 100, with exactly one missing.

Complexity: Time O(n); space O(1) beyond the input.

CodingEasyQA / SDET

4. Write a program to find the area of an equilateral triangle.

Model answer

// Read the side length from standard input and calculate the triangle's area.
const fs = require('fs');
const input = fs.readFileSync(0, 'utf8').trim();
const side = Number(input);

if (!Number.isFinite(side) || side < 0) {
  console.error('Enter a non-negative side length.');
  process.exit(1);
}

const area = (Math.sqrt(3) / 4) * side * side;
console.log(area);
  • Uses the equilateral-triangle formula: area = (√3 / 4) × side².
  • Provide the side length on standard input; the result is printed to standard output.
  • Complexity: O(1) time and O(1) space.
CodingMediumQA / SDET

5. Write test cases for a lift.

Model answer

const test = require('node:test');
const assert = require('node:assert/strict');

// Small lift model used to make the expected behavior testable.
class Lift {
  constructor(minFloor = 0, maxFloor = 10, startFloor = 0) {
    if (startFloor < minFloor || startFloor > maxFloor) {
      throw new RangeError('Starting floor is out of range');
    }
    this.minFloor = minFloor;
    this.maxFloor = maxFloor;
    this.currentFloor = startFloor;
    this.requests = [];
    this.doorOpen = false;
  }

  requestFloor(floor) {
    if (!Number.isInteger(floor) || floor < this.minFloor || floor > this.maxFloor) {
      throw new RangeError('Requested floor is out of range');
    }

    if (floor === this.currentFloor && this.requests.length === 0) {
      this.doorOpen = true;
    } else if (!this.requests.includes(floor)) {
      this.requests.push(floor);
    }
  }

  advance() {
    if (this.doorOpen) throw new Error('Cannot move while doors are open');
    if (this.requests.length === 0) return;

    const target = this.requests[0];
    this.currentFloor += Math.sign(target - this.currentFloor);

    if (this.currentFloor === target) {
      this.requests.shift();
      this.doorOpen = true;
    }
  }

  closeDoor(obstructed = false) {
    if (obstructed) return false; // Safety: keep doors open if obstructed.
    this.doorOpen = false;
    return true;
  }
}

test('moves to a requested floor and opens the doors on arrival', () => {
  const lift = new Lift(0, 5, 0);
  lift.requestFloor(2);
  lift.advance();
  assert.equal(lift.currentFloor, 1);
  lift.advance();
  assert.equal(lift.currentFloor, 2);
  assert.equal(lift.doorOpen, true);
  assert.deepEqual(lift.requests, []);
});

test('rejects floors outside the building', () => {
  const lift = new Lift(0, 5, 0);
  assert.throws(() => lift.requestFloor(6), RangeError);
  assert.throws(() => lift.requestFloor(-1), RangeError);
});

test('does not move with doors open', () => {
  const lift = new Lift(0, 5, 0);
  lift.requestFloor(1);
  lift.advance(); // Arrives and opens the doors.
  assert.throws(() => lift.advance(), /doors are open/);
});

test('keeps doors open when an obstruction is detected', () => {
  const lift = new Lift(0, 5, 0);
  lift.requestFloor(0);
  assert.equal(lift.doorOpen, true);
  assert.equal(lift.closeDoor(true), false);
  assert.equal(lift.doorOpen, true);
  assert.equal(lift.closeDoor(false), true);
  assert.equal(lift.doorOpen, false);
});
  • These tests cover normal travel, floor boundaries, the door/movement interlock, and obstruction safety. In a real project, I would also test capacity limits, emergency stop, power failure, and concurrent requests against the lift controller interface.
  • Run with node --test lift.test.js.

Complexity: Each movement step is O(1); request de-duplication is O(n) in the number of pending requests. Space is O(n).

CodingMediumQA / SDET

6. Given str1 = "makemytrip" and str2 = "mmakemyprit", write a program to convert str2 into str1.

Model answer

// Build a minimum-edit Levenshtein plan, then apply it to the source string.
function convert(source, target) {
  const m = source.length;
  const n = target.length;
  const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));

  for (let i = m; i >= 0; i--) dp[i][n] = m - i;
  for (let j = n; j >= 0; j--) dp[m][j] = n - j;

  for (let i = m - 1; i >= 0; i--) {
    for (let j = n - 1; j >= 0; j--) {
      dp[i][j] = source[i] === target[j]
        ? dp[i + 1][j + 1]
        : 1 + Math.min(dp[i + 1][j], dp[i][j + 1], dp[i + 1][j + 1]);
    }
  }

  const chars = [...source];
  const operations = [];
  let i = 0;
  let j = 0;

  while (i < m || j < n) {
    if (i < m && j < n && source[i] === target[j]) {
      i++;
      j++;
    } else if (i < m && dp[i][j] === 1 + dp[i + 1][j]) {
      operations.push(`Delete '${chars[i]}' at index ${i}`);
      chars.splice(i, 1);
      i++;
    } else if (j < n && dp[i][j] === 1 + dp[i][j + 1]) {
      operations.push(`Insert '${target[j]}' at index ${i}`);
      chars.splice(i, 0, target[j]);
      i++;
      j++;
    } else {
      operations.push(`Replace '${chars[i]}' with '${target[j]}' at index ${i}`);
      chars[i] = target[j];
      i++;
      j++;
    }
  }

  return { operations, result: chars.join('') };
}

const { operations, result } = convert('mmakemyprit', 'makemytrip');
console.log(operations.join('\n'));
console.log('Result:', result);
  • Uses dynamic programming to find a minimum sequence of insertions, deletions, and replacements.
  • Indices in each operation refer to the string as it changes; the final result is makemytrip.
  • Complexity: O(mn) time and space, where m and n are the string lengths.
CodingMediumQA / SDET

7. Write SQL to retrieve data from databases X, Y, and Z.

Model answer

The schemas and table names are not specified, so I’ll assume each database client exposes a fetchAll() method for the same logical dataset. Here is the JavaScript equivalent: fetch from all three concurrently, combine the results, and report any source failures.

async function retrieveFromAll(dbX, dbY, dbZ) {
  const sources = [
    ["X", dbX],
    ["Y", dbY],
    ["Z", dbZ],
  ];

  // Query all databases concurrently so one slow source does not delay starting others.
  const results = await Promise.allSettled(
    sources.map(([, db]) => db.fetchAll())
  );

  const rows = [];
  const errors = [];

  results.forEach((result, index) => {
    const [source] = sources[index];

    if (result.status === "fulfilled") {
      // Preserve source identity when combining records.
      for (const row of result.value) {
        rows.push({ ...row, source });
      }
    } else {
      errors.push({ source, message: result.reason?.message ?? String(result.reason) });
    }
  });

  return { rows, errors };
}

// Each client implements fetchAll() and returns an array of records.
// const result = await retrieveFromAll(dbX, dbY, dbZ);
// console.log(result.rows, result.errors);
  • Promise.allSettled allows successful sources to return data even if another source fails.
  • If all three sources must succeed, use Promise.all instead and fail the operation when any request rejects.

Complexity: Time O(N) to combine N returned records; space O(N).

CodingMediumQA / SDET

8. Given the matrix 1 2 3 / 4 5 6 / 7 8 9, write a program to print the values in the order 1 2 3 6 9 8 7 4 5.

Model answer

function spiralOrder(matrix) {
  if (matrix.length === 0 || matrix[0].length === 0) return [];

  const result = [];
  let top = 0;
  let bottom = matrix.length - 1;
  let left = 0;
  let right = matrix[0].length - 1;

  while (top <= bottom && left <= right) {
    // Traverse the top row from left to right.
    for (let col = left; col <= right; col++) {
      result.push(matrix[top][col]);
    }
    top++;

    // Traverse the right column from top to bottom.
    for (let row = top; row <= bottom; row++) {
      result.push(matrix[row][right]);
    }
    right--;

    // Traverse the bottom row from right to left, if it remains.
    if (top <= bottom) {
      for (let col = right; col >= left; col--) {
        result.push(matrix[bottom][col]);
      }
      bottom--;
    }

    // Traverse the left column from bottom to top, if it remains.
    if (left <= right) {
      for (let row = bottom; row >= top; row--) {
        result.push(matrix[row][left]);
      }
      left++;
    }
  }

  return result;
}

const matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];

console.log(spiralOrder(matrix).join(" ")); // 1 2 3 6 9 8 7 4 5
  • Track the unvisited rectangle with top, bottom, left, and right boundaries; shrink each boundary after traversing it.
  • The boundary checks prevent revisiting cells in single-row or single-column inner layers.

Complexity: Time O(rows × columns); space O(rows × columns) for the returned values.

CodingMediumQA / SDET

9. Write a shell script to find the word with the most occurrences in a file.

Model answer

// Usage: node mostFrequentWord.js <file>
const fs = require('node:fs');

const filePath = process.argv[2];
if (!filePath) {
  console.error('Usage: node mostFrequentWord.js <file>');
  process.exit(1);
}

try {
  const text = fs.readFileSync(filePath, 'utf8');
  // Count letter/number words, allowing internal apostrophes; compare case-insensitively.
  const words = text.match(/[\p{L}\p{N}_]+(?:['’][\p{L}\p{N}_]+)*/gu) || [];
  const counts = new Map();

  for (const word of words) {
    const normalized = word.toLocaleLowerCase();
    counts.set(normalized, (counts.get(normalized) || 0) + 1);
  }

  if (counts.size === 0) {
    console.log('No words found.');
    process.exit(0);
  }

  const highestCount = Math.max(...counts.values());
  for (const [word, count] of counts) {
    if (count === highestCount) console.log(`${word}: ${count}`);
  }
} catch (error) {
  console.error(`Could not read file: ${error.message}`);
  process.exit(1);
}
  • Tokenize the file, normalize words to lowercase, and count them in a map.
  • Print every word tied for the highest frequency.

Complexity: O(n) time for n characters and O(u) space for u distinct words.

Product & growthMediumQA / SDET

10. How can you see the same ads on multiple sites—for example, after visiting Amazon.com and adding a product to your cart, seeing that product advert…

The full question

How can you see the same ads on multiple sites—for example, after visiting Amazon.com and adding a product to your cart, seeing that product advertised on Facebook?

Model answer

Clarify & scope

I’d explain this as retargeting: an advertiser tries to show relevant ads to people who previously interacted with its site. The exact product a person sees depends on available identifiers, consent, ad inventory, and the platform’s policies; it is not necessarily Amazon directly sending Facebook a list of shoppers.

User segments & pain points

The relevant segment is a shopper who viewed or added an item to a cart but did not purchase. The advertiser wants to remind them about the item, while the shopper may find repeated ads intrusive or be concerned about how their activity was linked.

Goals & success metrics

The advertiser’s goal is incremental purchases, measured through conversion lift against a control group—not just clicks or impressions. Guardrails include frequency per person, opt-out and complaint rates, privacy-policy compliance, and avoiding ads for items already purchased.

Solutions

  • Site tracking: Amazon, or an advertiser using a similar setup, can record an event such as add_to_cart through a site tag or server-side integration. A browser identifier may help associate later ad requests with that activity, subject to browser restrictions and user consent.
  • Audience matching: The advertiser can make an eligible audience available to an ad platform. Depending on permissions and platform rules, matching may use a browser identifier or privacy-protected account matching; the platform then selects an ad when that person visits a participating surface.
  • Ad delivery: The ad can be personalized to the product or category, and a frequency cap can limit how often it appears. Purchases or opt-outs should remove or suppress the shopper from the audience where supported.
flowchart LR
  A[Shopper visits store] --> B[Eligible activity recorded]
  B --> C[Audience matched under platform rules]
  C --> D[Shopper visits another site]
  D --> E[Ad auction selects relevant ad]
Diagram

Recommendation: Describe it as consent- and policy-governed audience matching plus ad selection, rather than as one site simply following a person everywhere. Tracking can be limited by cookie controls, private browsing, ad blockers, or platform restrictions.

Prioritization & trade-offs

I’d prioritize clear consent, purchase suppression, and frequency caps before increasing personalization. More data may improve relevance, but it also increases privacy risk and can reduce user trust.

MVP, measurement & rollout

Start with a consented audience and a small holdout group. Compare incremental conversion and revenue per eligible shopper, then review frequency, opt-outs, complaints, and policy compliance before expanding.

System designMediumQA / SDETOnline assessment

11. How would you implement a Find My Device feature?

Model answer

1. Requirements & scale

  • Functional: Let an authenticated owner see a device’s last known location and timestamp, request a fresh location, play a sound, lock it, or erase it. Show whether the device is offline and whether an action is pending or completed.
  • Non-functional: Protect location data with strong authentication, authorization, encryption, and auditability. Make location freshness and uncertainty explicit; tolerate intermittent connectivity and avoid battery-draining polling.
  • Assumptions: 10 million opted-in devices; location reports are sent every 15 minutes while eligible. Users can revoke access, and an erased or revoked device stops reporting.

Back-of-the-envelope: 10M × 96 reports/day ≈ 960M reports/day, or 11K writes/s average; design for 5× peak, about 55K writes/s. At roughly 1 KB per report, raw location storage is ~1 TB/day before indexes and replication; retain only a short history (for example, seven days) and compact older records. If 1M owners check once daily, average read QPS is ~12; allow for traffic spikes and incident-driven bursts. Location payload bandwidth is roughly 11 MB/s average before protocol overhead.

2. High-level architecture

flowchart TD
  subgraph Client["Client"]
    U["Owner app"]
    D["Registered device"]
  end
  subgraph Edge["Edge/CDN"]
    E["TLS edge and rate limits"]
  end
  subgraph LB["Load Balancer"]
    L["Regional API routing"]
  end
  subgraph Services["API / Services"]
    A["Auth and device API"]
    P["Location and action service"]
    N["Push gateway"]
  end
  subgraph Cache["Cache"]
    C["Short-lived device state"]
  end
  subgraph Stores["Datastores"]
    S["Device and ownership SQL"]
    G["Latest location store"]
    H["Encrypted location history"]
  end
  subgraph Queue["Message Queue"]
    Q["Location and command events"]
  end
  subgraph Workers["Workers"]
    W["Ingestion and retention workers"]
    X["Command and notification workers"]
  end
  U -->|"TLS API requests"| E --> L --> A
  A -->|"ownership and consent"| S
  A -->|"read or command"| P
  P -->|"latest state"| C
  P -->|"location lookup"| G
  P -->|"enqueue command"| Q
  D -->|"signed location reports"| E
  E --> L --> A -->|"validated report"| Q
  Q --> W -->|"latest location"| G
  W -->|"append encrypted history"| H
  Q --> X --> N -->|"wake or action push"| D
  D -->|"action result"| E
Diagram

3. API design

  • GET /v1/devices — list devices visible to the authenticated owner.
  • GET /v1/devices/{id}/location — return coordinates, accuracy radius, source, and captured_at; never imply a stale location is current.
  • POST /v1/devices/{id}/locate — request a fresh fix; return a request ID and pending status.
  • POST /v1/devices/{id}/actions — request ring, lock, or erase; require step-up authentication for destructive actions.
  • POST /v1/devices/{id}/location-reports — accept device-signed, timestamped reports with an idempotency key.
  • DELETE /v1/devices/{id}/sharing — revoke reporting and invalidate outstanding commands.

4. Data model & storage

  • SQL: Device(id, owner_id, public_key, status, consent_version) and Action(id, device_id, type, state, created_at, expires_at). Enforce ownership checks transactionally; index devices by owner_id.
  • Latest location: A key-value or wide-column store keyed by device_id, storing the newest accepted report, accuracy, and capture time. Conditional writes reject older reports.
  • History: Encrypted, time-partitioned location records keyed by device_id and time; TTL removes data after the retention period. Keep history optional and minimize precision and retention.
  • Cache only short-lived, non-authoritative device state. Do not cache location responses across owners or beyond their freshness window.

5. Deep dive

The core challenge is delivering useful location despite offline devices without turning a location feature into continuous surveillance. Devices report only under explicit consent and suitable battery/network conditions. A report includes device ID, monotonic sequence number, capture time, coordinates, accuracy, and a signature. The service verifies the signature, device status, consent, and timestamp bounds before accepting it. Idempotency plus sequence checks prevent replay and out-of-order updates.

For a fresh-location request, the service authorizes the owner, creates a short-lived request ID, and sends a push wake-up. The device obtains a fix, returns a signed report, and the UI updates with its age and accuracy. If the device does not respond before the deadline, return the last known fix marked stale, or “location unavailable”; do not present an old fix as live. Commands are also expiring, acknowledged state transitions, not fire-and-forget calls. Erase requires explicit confirmation and step-up authentication, and the device must acknowledge it when reachable.

sequenceDiagram
  participant O as Owner app
  participant API as Location service
  participant DB as Ownership store
  participant Q as Command queue
  participant D as Device
  O->>API: Request fresh location
  API->>DB: Verify owner and consent
  DB-->>API: Authorized
  API->>Q: Enqueue expiring locate request
  API-->>O: Request ID and pending state
  Q-->>D: Push wake-up
  D->>API: Signed location report
  API->>DB: Validate device and consent
  API-->>O: Location, age, accuracy
Diagram

As a QA/SDET, I would make correctness observable through request IDs, command state transitions, and audit events. Test signature and authorization failures, replay and out-of-order reports, stale/offline behavior, revocation races, push delays, and duplicate delivery. Use deterministic clocks and simulated devices for boundary cases, plus load tests at peak ingestion and fault injection for queue and datastore outages.

6. Scale, bottlenecks & trade-offs

  • Partition location data by device ID; replicate across availability zones. Keep ownership and consent authoritative in SQL, with backups and tested recovery procedures.
  • Queue ingestion to absorb bursts and isolate device reporting from storage slowness. Apply backpressure and sampling rather than silently dropping security or consent checks; alert on queue age and report rejection rates.
  • Use push for low-latency wake-up, but retain pull/reporting as a fallback because mobile push is best-effort. Offline devices cannot be located or commanded; return that limitation clearly.
  • Prefer strong authorization and consent checks over availability during an ownership-store outage. Stale location reads may be available with an explicit timestamp, but destructive actions fail closed.
  • Monitor location freshness, action completion latency, battery impact, unauthorized-access attempts, and deletion/retention compliance. Keep precise location out of general analytics and logs.
TechnicalEasyQA / SDET

12. What are the different types of waits in Selenium?

Model answer

The main Selenium wait types are:

  1. Implicit wait — A session-wide timeout for finding elements. Selenium retries element lookup until the element appears or the timeout expires. ``java driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5)); ``
  2. Explicit wait — Waits for a specific condition, such as visibility, clickability, or a URL change. It is usually the clearest choice for synchronizing with a UI state. ``java WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); wait.until(ExpectedConditions.elementToBeClickable(By.id("continue"))).click(); ``
  3. Fluent wait — A configurable explicit wait: set the polling interval and exceptions to ignore. WebDriverWait is a specialized FluentWait<WebDriver>.
  4. Static wait (Thread.sleep) — Pauses for a fixed duration. It is not a Selenium wait and is generally a poor choice: it can waste time when the page is ready early and still fail when it is not ready after the pause.

Selenium also provides timeout settings for page loads and asynchronous scripts; these are separate from the element-wait types above. In most UI tests, prefer explicit waits for the exact condition and avoid mixing implicit and explicit waits.

TechnicalEasyQA / SDET

13. What are fluent waits in Selenium?

Model answer

A fluent wait repeatedly checks a condition until it succeeds or a timeout expires. It lets you configure the total timeout, polling interval, and exceptions to ignore.

In Java, Selenium’s FluentWait<WebDriver> is the general-purpose implementation; WebDriverWait extends it and is commonly used with ExpectedConditions.

Wait<WebDriver> wait = new FluentWait<>(driver)
    .withTimeout(Duration.ofSeconds(15))
    .pollingEvery(Duration.ofMillis(500))
    .ignoring(NoSuchElementException.class);

WebElement result = wait.until(d -> {
    WebElement element = d.findElement(By.id("search-result"));
    return element.isDisplayed() ? element : null;
});

The wait polls every 500 ms, ignores a missing-element exception while polling, and returns the element when the condition is true. If the timeout expires, it throws a timeout exception.

Use fluent waits for UI states that can take a variable amount of time, such as search results loading. Avoid combining implicit and explicit waits, as their timeout behavior can become unpredictable.

TechnicalEasyQA / SDET

14. What is the difference between a cache and cookies?

Model answer

A cache stores data temporarily so it can be reused without fetching or computing it again. Cookies are small pieces of data a website stores in a browser, commonly to maintain a session or remember preferences.

  • Purpose: Caches improve performance; cookies carry client-related state or identifiers.
  • Where they live: Browser caches may store files such as images and scripts. Cookies are stored by the browser and sent to matching servers with HTTP requests, subject to their scope and security settings.
  • Lifetime and control: Cache entries are governed by cache policies such as Cache-Control and validators such as ETag. Cookies have attributes such as Expires or Max-Age, Secure, HttpOnly, and SameSite.
  • Example: A MakeMyTrip logo image may be cached to load quickly; a session cookie may help the site recognize a signed-in user.

A cookie is not itself a cache, though browsers may cache responses that set cookies according to HTTP caching rules.

TechnicalEasyQA / SDET

15. What is the difference between a class and an interface in Java?

Model answer

A class provides an implementation and can hold state; an interface defines a contract that implementing types agree to follow.

  • A class can have instance fields, constructors, and concrete methods. It can extend one class.
  • An interface cannot be instantiated and has no constructors. Its fields are implicitly public static final; it can declare abstract methods and, in modern Java, default, static, and private methods.
  • A class uses extends to inherit from a class and implements to fulfill interfaces. It can implement multiple interfaces, which supports multiple contracts without multiple class inheritance.
  • Use a class when modeling an implementation with state or shared behavior; use an interface when defining a capability that different classes can implement.

For example, PaymentProvider could be an interface implemented by separate card and wallet payment classes.

TechnicalEasyQA / SDET

16. How would you replace all occurrences of a word in a Unix file?

Model answer

Use sed with the global substitution flag:

sed -i 's/old_word/new_word/g' file.txt

g replaces every match on each line. To avoid modifying the original, write to a temporary file and then replace it:

sed 's/old_word/new_word/g' file.txt > file.txt.tmp && mv file.txt.tmp file.txt

This treats the search text as a pattern. If you need to match a whole word only, use word-boundary syntax supported by your sed implementation, or use a tool such as Perl. Be careful with replacement text containing / or &; those characters need escaping in sed.

TechnicalEasyQA / SDET

17. What is an entry set?

Model answer

entrySet() is a method on Java’s Map interface. It returns a Set<Map.Entry<K, V>> containing the map’s key-value pairs.

Map<String, Integer> counts = Map.of("flight", 3, "hotel", 5);

for (Map.Entry<String, Integer> entry : counts.entrySet()) {
    System.out.println(entry.getKey() + "=" + entry.getValue());
}

It is useful when you need both the key and value while iterating. The returned set is generally backed by the map, so changes to the map are reflected in it; whether entries can be modified depends on the map implementation.

TechnicalEasyQA / SDET

18. What is the purpose of the top command?

Model answer

  1. top is an interactive, real-time view of processes running on a Unix-like system. It helps inspect system load and identify processes consuming resources.
  2. The summary typically shows uptime, load averages, CPU usage, memory, and swap. The process table commonly includes PID, user, CPU and memory usage, state, and command.
  3. It refreshes periodically; common keys include q to quit, P to sort by CPU, and M to sort by memory. It is useful for diagnosing high CPU or memory usage, but is a snapshot rather than a historical monitoring tool.
TechnicalEasyQA / SDET

19. What are the purposes of the df and du commands?

Model answer

  • df reports filesystem-level disk space usage: total, used, and available capacity for mounted filesystems. For readable units, use df -h.
  • du estimates how much disk space files or directories consume. For example, du -sh directory/ gives a readable summary for that directory.

In short, use df to check space available on a filesystem and du to find which files or directories are using space.

TechnicalEasyQA / SDET

20. Can WHERE and HAVING clauses be used in the same SQL query?

Model answer

Yes. WHERE filters individual rows before grouping and aggregation; HAVING filters the resulting groups after aggregation.

SELECT department_id, AVG(salary) AS average_salary
FROM employees
WHERE status = 'ACTIVE'
GROUP BY department_id
HAVING AVG(salary) > 50000;

This considers only active employees, groups them by department, then returns departments whose average salary exceeds 50,000.

Practice these out loud, don't memorise them

Reading an answer is not the same as being able to give one under pressure. ChannelPulse plays the interviewer, asks the follow-ups, and scores each answer with feedback and a model answer so you can hear the gap between what you said and what lands.

Get ChannelPulse Browse all questions