Skip to content

Practical Blockchain Interview Questions

41 questions with answers. Hands-on questions where you write code, a query, a formula or concrete steps.

How to approach these questions

Talk while you work: say your approach first, write the simplest correct version, then improve it and mention edge cases.

Solved — practicalStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
3 questions free Unlock the rest in seconds
01

Write a minimal Python example showing how blocks are linked by hashes.

Save to ▾
Show answer
Each block stores the previous hash, so changing any earlier data breaks the chain. import hashlib, json def block_hash(block): data = json.dumps(block, sort_keys=True).encode() return hashlib.sha256(data).hexdigest() chain = [{'index': 0, 'data': 'genesis', 'prev': '0'}] for i, tx in enumerate(['A pays B 5', 'B pays C 2'], 1): chain.append({'index': i, 'data': tx, 'prev': block_hash(chain[-1])}) valid = all(chain[i]['prev'] == block_hash(chain[i-1]) for i in range(1, len(chain))) print(valid)
02

You open a transaction on a block explorer. Which fields do you check and what do they mean?

Save to ▾
Show answer
Check the status (success or failed), the block number and confirmations, from and to addresses, and the value transferred. For contract calls, check the decoded input data and emitted event logs, which show token transfers. Check the gas limit, gas used and effective gas price, which together give the fee paid, plus the nonce. If the status failed, the revert reason tells you why, while fees are still charged for gas used.
03

How do you get the latest block number from an Ethereum node using JSON-RPC?

Save to ▾
Show answer
Send a JSON-RPC POST request to the node or provider URL. The result is a hex string that you convert to decimal. curl -s -X POST https://rpc.example.org \ -H 'Content-Type: application/json' \ -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' # Response: {"jsonrpc":"2.0","id":1,"result":"0x15d3a1c"} # In Python: int('0x15d3a1c', 16) Other common methods are eth_getBalance, eth_call and eth_getTransactionReceipt.
04

How would you set up a local blockchain for development and testing?

Save to ▾
Show answer
For EVM work, run a local node with Anvil from Foundry or the Hardhat network. Each gives about ten pre-funded test accounts, instant mining and console logging. You can fork mainnet at a given block to test against real contracts and balances without spending money. For integration tests, deploy to a public testnet such as Sepolia, using faucet ETH. Keep deploy scripts and RPC URLs in config so the same code targets local, testnet and mainnet.
05

How do you compute a keccak256 hash in Solidity and in ethers.js?

Save to ▾
Show answer
Solidity: bytes32 h1 = keccak256(abi.encodePacked('hello')); bytes32 h2 = keccak256(abi.encode(addr, amount)); ethers v6: import { keccak256, toUtf8Bytes, solidityPackedKeccak256 } from 'ethers'; const h = keccak256(toUtf8Bytes('hello')); const p = solidityPackedKeccak256(['address','uint256'], [addr, amount]); Prefer abi.encode over abi.encodePacked when hashing several dynamic values, because packed encoding can cause collisions.
06

How do you verify a signed message inside a Solidity contract?

Save to ▾
Show answer
Recompute the message hash, add the Ethereum signed message prefix, recover the signer and compare it. import {ECDSA} from '@openzeppelin/contracts/utils/cryptography/ECDSA.sol'; import {MessageHashUtils} from '@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol'; function verify(address signer, uint256 amount, uint256 nonce, bytes calldata sig) public view returns (bool) { bytes32 h = keccak256(abi.encode(address(this), block.chainid, amount, nonce)); bytes32 eth = MessageHashUtils.toEthSignedMessageHash(h); return ECDSA.recover(eth, sig) == signer; } Track used nonces to block replays.
07

Show how to sign and verify a message with ethers.js.

Save to ▾
Show answer
With ethers v6, a wallet signs using EIP-191 personal sign, and verifyMessage recovers the address. import { Wallet, verifyMessage } from 'ethers'; const wallet = Wallet.createRandom(); const message = 'Login nonce: 48213'; const signature = await wallet.signMessage(message); const recovered = verifyMessage(message, signature); console.log(recovered === wallet.address); // true This pattern powers Sign-In with Ethereum; the server issues a fresh nonce each time to stop replay.
08

Write a Python function that computes a Merkle root from a list of transactions.

Save to ▾
Show answer
Hash leaves, then hash pairs until one remains, duplicating the last hash when a level is odd (Bitcoin style). import hashlib def h(b): return hashlib.sha256(b).digest() def merkle_root(txs): level = [h(t.encode()) for t in txs] while len(level) > 1: if len(level) % 2: level.append(level[-1]) level = [h(level[i] + level[i+1]) for i in range(0, len(level), 2)] return level[0].hex() print(merkle_root(['tx1', 'tx2', 'tx3']))
09

Write a simple Proof of Work loop in Python with a difficulty setting.

Save to ▾
Show answer
The miner increments the nonce until the hash starts with the required number of zero hex digits. import hashlib def mine(data, difficulty=4): prefix = '0' * difficulty nonce = 0 while True: h = hashlib.sha256(f'{data}{nonce}'.encode()).hexdigest() if h.startswith(prefix): return nonce, h nonce += 1 print(mine('block-1: A pays B 5')) Each extra zero makes mining about 16 times harder, while verifying still needs one hash.
10

How do you deploy a contract to a Layer 2 testnet with Foundry?

Save to ▾
Show answer
Set the RPC URL and a deployer key, then use forge create or a script, and verify the source on the explorer. export RPC_URL=https://sepolia.l2-example.org export PRIVATE_KEY=0x... # testnet key only forge create src/Counter.sol:Counter \ --rpc-url $RPC_URL --private-key $PRIVATE_KEY --broadcast # Scripted deploy with verification forge script script/Deploy.s.sol --rpc-url $RPC_URL \ --broadcast --verify Use a keystore via cast wallet import instead of raw keys for anything real.
11

How do you read the latest finalized block with ethers.js, and why use it?

Save to ▾
Show answer
Pass the block tag to getBlock. The finalized tag returns the latest block that Proof of Stake has finalised, which cannot be reverted without slashing a third of stake. import { JsonRpcProvider } from 'ethers'; const provider = new JsonRpcProvider(process.env.RPC_URL); const latest = await provider.getBlock('latest'); const safe = await provider.getBlock('safe'); const finalized = await provider.getBlock('finalized'); console.log(latest.number - finalized.number); // usually about 64-96 Use finalized for deposits and accounting; use latest for UI updates.
12

How do you read a contract's storage slot directly with Foundry's cast?

Save to ▾
Show answer
Use cast storage with the contract address and slot number. For mappings, compute the slot as keccak256(key . slot). # Read slot 0 (often the first state variable) cast storage 0xContractAddress 0 --rpc-url $RPC_URL # balanceOf mapping stored at slot 2, key = user address cast index address 0xUserAddress 2 cast storage 0xContractAddress <slot-from-above> --rpc-url $RPC_URL This shows that private variables are not secret: anyone can read storage.
13

How do you compute a function selector and decode calldata with cast?

Save to ▾
Show answer
cast handles ABI work from the command line. # Function selector cast sig 'transfer(address,uint256)' # 0xa9059cbb # Encode calldata cast calldata 'transfer(address,uint256)' 0xAbc... 1000000 # Decode calldata from a transaction cast 4byte-decode 0xa9059cbb000000... # Decode with a known signature cast decode-calldata 'transfer(address,uint256)' 0xa9059cbb... This is useful when checking what a wallet is really asking you to sign.
14

How do you get current fee data and send an EIP-1559 transaction with ethers.js?

Save to ▾
Show answer
ethers v6 provides getFeeData, and sendTransaction fills in fields automatically, but you can set them explicitly. import { JsonRpcProvider, Wallet, parseEther } from 'ethers'; const provider = new JsonRpcProvider(process.env.RPC_URL); const wallet = new Wallet(process.env.PRIVATE_KEY, provider); const fee = await provider.getFeeData(); const tx = await wallet.sendTransaction({ to: '0xRecipient...', value: parseEther('0.01'), maxFeePerGas: fee.maxFeePerGas, maxPriorityFeePerGas: fee.maxPriorityFeePerGas }); const receipt = await tx.wait(); console.log(receipt.status);
15

Write a simple ERC-20 token using OpenZeppelin.

Save to ▾
Show answer
Inherit the audited ERC20 implementation and mint the initial supply in the constructor. // SPDX-License-Identifier: MIT pragma solidity ^0.8.24; import {ERC20} from '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import {Ownable} from '@openzeppelin/contracts/access/Ownable.sol'; contract CampusToken is ERC20, Ownable { constructor() ERC20('Campus Token', 'CAMP') Ownable(msg.sender) { _mint(msg.sender, 1_000_000 * 10 ** decimals()); } function mint(address to, uint256 amount) external onlyOwner { _mint(to, amount); } }
16

Write a Foundry unit test and a fuzz test for a contract.

Save to ▾
Show answer
Foundry tests are Solidity contracts; functions starting with test run as tests, and parameters make them fuzz tests. import {Test} from 'forge-std/Test.sol'; import {Vault} from '../src/Vault.sol'; contract VaultTest is Test { Vault v; function setUp() public { v = new Vault(); } function testDeposit() public { v.deposit{value: 1 ether}(); assertEq(v.balanceOf(address(this)), 1 ether); } function testFuzzDeposit(uint96 amt) public { vm.assume(amt > 0); vm.deal(address(this), amt); v.deposit{value: amt}(); assertEq(address(v).balance, amt); } } Run with forge test -vvv.
17

Write a simple escrow contract where a buyer deposits and releases payment to a seller.

Save to ▾
Show answer
pragma solidity ^0.8.24; contract Escrow { address public immutable buyer; address payable public immutable seller; bool public released; constructor(address payable _seller) payable { buyer = msg.sender; seller = _seller; } function release() external { require(msg.sender == buyer, 'only buyer'); require(!released, 'done'); released = true; (bool ok, ) = seller.call{value: address(this).balance}(''); require(ok, 'transfer failed'); } } State is updated before the external call to follow checks-effects-interactions.
18

Write a basic voting contract using a struct, mapping and event.

Save to ▾
Show answer
pragma solidity ^0.8.24; contract Voting { struct Proposal { string name; uint256 votes; } Proposal[] public proposals; mapping(address => bool) public hasVoted; event Voted(address indexed voter, uint256 indexed id); constructor(string[] memory names) { for (uint256 i; i < names.length; i++) proposals.push(Proposal(names[i], 0)); } function vote(uint256 id) external { require(!hasVoted[msg.sender], 'already voted'); hasVoted[msg.sender] = true; proposals[id].votes++; emit Voted(msg.sender, id); } } An out-of-range id reverts automatically.
19

Show a contract vulnerable to reentrancy and a fixed version.

Save to ▾
Show answer
Vulnerable: the balance is cleared after sending. function withdraw() external { uint256 bal = balances[msg.sender]; (bool ok, ) = msg.sender.call{value: bal}(''); require(ok); balances[msg.sender] = 0; } Fixed: update state first and add a guard. import {ReentrancyGuard} from '@openzeppelin/contracts/utils/ReentrancyGuard.sol'; function withdraw() external nonReentrant { uint256 bal = balances[msg.sender]; require(bal > 0, 'nothing'); balances[msg.sender] = 0; (bool ok, ) = msg.sender.call{value: bal}(''); require(ok, 'send failed'); }
20

How do you run Slither on a Foundry project and focus on important findings?

Save to ▾
Show answer
Install it with pip and run it from the project root; it detects Foundry automatically. pip install slither-analyzer slither . # Only medium and high impact issues slither . --exclude-low --exclude-informational # Exclude dependencies slither . --filter-paths 'lib|test' # Print a summary of contracts and functions slither . --print human-summary Triage each finding: fix real bugs and record why false positives are safe.
21

Write a Foundry invariant test for a token's total supply.

Save to ▾
Show answer
Invariant tests call random functions on target contracts and check a property after every call. import {Test} from 'forge-std/Test.sol'; import {MyToken} from '../src/MyToken.sol'; import {Handler} from './Handler.sol'; contract SupplyInvariant is Test { MyToken token; Handler handler; function setUp() public { token = new MyToken(); handler = new Handler(token); targetContract(address(handler)); } function invariant_supplyMatchesBalances() public view { assertEq(token.totalSupply(), handler.sumOfBalances()); } } The handler bounds inputs and tracks actors so calls stay realistic.
22

Calculate the output of a swap in a constant product pool with a 0.3 percent fee.

Save to ▾
Show answer
Formula: amountOut = (amountIn x 997 x reserveOut) / (reserveIn x 1000 + amountIn x 997). Example: reserves 1,000 ETH and 3,000,000 USDC, swap 10 ETH. amountInWithFee = 10 x 997 = 9,970 numerator = 9,970 x 3,000,000 = 29,910,000,000 denominator = 1,000 x 1000 + 9,970 = 1,009,970 amountOut = 29,615 USDC (approx) The spot price is 3,000, but the trader gets about 2,961.5 per ETH because of fee and price impact.
23

Write a basic ERC-721 NFT contract using OpenZeppelin.

Save to ▾
Show answer
// SPDX-License-Identifier: MIT pragma solidity ^0.8.24; import {ERC721} from '@openzeppelin/contracts/token/ERC721/ERC721.sol'; import {Ownable} from '@openzeppelin/contracts/access/Ownable.sol'; contract CertificateNFT is ERC721, Ownable { uint256 public nextId; string private baseURI; constructor(string memory uri) ERC721('Course Cert', 'CERT') Ownable(msg.sender) { baseURI = uri; } function mint(address to) external onlyOwner { _safeMint(to, nextId++); } function _baseURI() internal view override returns (string memory) { return baseURI; } }
24

How do you calculate a borrower's health factor in a lending protocol?

Save to ▾
Show answer
Health factor = (sum of collateral value x liquidation threshold) / total debt value. Below 1, the position can be liquidated. Example: collateral 10 ETH at 3,000 dollars = 30,000 dollars, liquidation threshold 80 percent, debt 18,000 dollars of stablecoins. HF = (30,000 x 0.80) / 18,000 = 1.33. If ETH falls to 2,250, collateral is 22,500, so HF = 18,000 / 18,000 = 1.0 and liquidation begins. Users raise HF by repaying debt or adding collateral.
25

Write the core reward-per-token logic for a staking rewards contract.

Save to ▾
Show answer
uint256 public rewardRate; // tokens per second uint256 public rewardPerTokenStored; uint256 public lastUpdate; uint256 public totalStaked; mapping(address => uint256) public paid; mapping(address => uint256) public rewards; mapping(address => uint256) public staked; function rewardPerToken() public view returns (uint256) { if (totalStaked == 0) return rewardPerTokenStored; return rewardPerTokenStored + (block.timestamp - lastUpdate) * rewardRate * 1e18 / totalStaked; } modifier updateReward(address a) { rewardPerTokenStored = rewardPerToken(); lastUpdate = block.timestamp; rewards[a] += staked[a] * (rewardPerTokenStored - paid[a]) / 1e18; paid[a] = rewardPerTokenStored; _; }
26

How do you read a Chainlink price feed in Solidity safely?

Save to ▾
Show answer
import {AggregatorV3Interface} from '@chainlink/contracts/src/v0.8/shared/interfaces/AggregatorV3Interface.sol'; AggregatorV3Interface public feed; uint256 constant MAX_DELAY = 1 hours; function getPrice() public view returns (uint256) { (, int256 answer, , uint256 updatedAt, ) = feed.latestRoundData(); require(answer > 0, 'bad price'); require(block.timestamp - updatedAt <= MAX_DELAY, 'stale price'); return uint256(answer); // scale using feed.decimals(), often 8 } Always check staleness, sign and decimals; on L2s also check the sequencer uptime feed.
27

How do you build a tokenised vault using ERC-4626?

Save to ▾
Show answer
ERC-4626 standardises yield vaults: users deposit an asset and receive shares, and share price rises as the vault earns yield. import {ERC4626} from '@openzeppelin/contracts/token/ERC20/extensions/ERC4626.sol'; import {ERC20} from '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; contract YieldVault is ERC4626 { constructor(IERC20 asset_) ERC20('Vault Share', 'vSHR') ERC4626(asset_) {} function totalAssets() public view override returns (uint256) { return IERC20(asset()).balanceOf(address(this)); // plus deployed funds } } OpenZeppelin uses virtual shares to defend against the first-depositor inflation attack.
28

How do you approve and transfer ERC-20 tokens from a script with ethers.js?

Save to ▾
Show answer
import { Contract, parseUnits } from 'ethers'; const abi = [ 'function approve(address spender, uint256 amount) returns (bool)', 'function decimals() view returns (uint8)', 'function allowance(address owner, address spender) view returns (uint256)' ]; const token = new Contract(TOKEN_ADDRESS, abi, signer); const dec = await token.decimals(); const amount = parseUnits('25', dec); const tx = await token.approve(SPENDER, amount); await tx.wait(); console.log(await token.allowance(signer.address, SPENDER)); The spender contract then calls transferFrom to pull exactly that amount.
29

Calculate impermanent loss when one token's price doubles.

Save to ▾
Show answer
Formula: IL = 2 x sqrt(r) / (1 + r) - 1, where r is the price ratio change. For r = 2: sqrt(2) = 1.414, so IL = 2 x 1.414 / 3 - 1 = -0.057, about 5.7 percent. Example: deposit 1 ETH plus 3,000 USDC when ETH is 3,000 (6,000 dollars). ETH goes to 6,000. Holding would be 9,000 dollars; the pool position is worth about 8,485. Fees earned must exceed the 515 dollar gap for providing liquidity to beat holding.
30

How should NFT metadata and tokenURI be structured?

Save to ▾
Show answer
tokenURI(id) returns a URI, usually ipfs://<CID>/<id>.json, pointing to JSON that marketplaces read: { "name": "Course Certificate #12", "description": "Completed Blockchain Developer course", "image": "ipfs://bafy.../12.png", "attributes": [ { "trait_type": "Grade", "value": "A" }, { "trait_type": "Year", "value": 2026 } ] } Store images and JSON on IPFS or Arweave rather than a normal server, so metadata cannot silently change or disappear.
31

How do you connect a browser wallet to a dApp using ethers.js?

Save to ▾
Show answer
Browser wallets inject an EIP-1193 provider at window.ethereum. Wrap it with BrowserProvider and request accounts. import { BrowserProvider } from 'ethers'; async function connect() { if (!window.ethereum) throw new Error('Install a wallet'); const provider = new BrowserProvider(window.ethereum); const signer = await provider.getSigner(); // prompts the user const address = await signer.getAddress(); const { chainId } = await provider.getNetwork(); return { signer, address, chainId }; } In production, use EIP-6963 discovery or a connector library so users with several wallets can choose.
32

How do you call read and write functions of a contract with ethers v6?

Save to ▾
Show answer
Create a Contract with address, ABI and a provider for reads or a signer for writes. import { Contract, parseEther } from 'ethers'; const abi = [ 'function count() view returns (uint256)', 'function increment() payable' ]; const readOnly = new Contract(ADDR, abi, provider); console.log(await readOnly.count()); // free eth_call const writable = new Contract(ADDR, abi, signer); const tx = await writable.increment({ value: parseEther('0.001') }); const receipt = await tx.wait(); console.log(receipt.hash, receipt.status);
33

How do you listen to contract events and query past events with ethers?

Save to ▾
Show answer
Use contract.on for live events and queryFilter for history. const abi = ['event Transfer(address indexed from, address indexed to, uint256 value)']; const token = new Contract(TOKEN, abi, provider); token.on('Transfer', (from, to, value, event) => { console.log(from, to, value.toString(), event.log.blockNumber); }); const filter = token.filters.Transfer(null, MY_ADDRESS); const past = await token.queryFilter(filter, -5000); // last 5000 blocks console.log(past.length); Use a WebSocket provider for live events, and page large ranges because providers limit block spans.
34

How do you read a contract and send a transaction with viem?

Save to ▾
Show answer
viem is a typed, lightweight alternative to ethers, and wagmi builds React hooks on it. import { createPublicClient, createWalletClient, http, custom } from 'viem'; import { sepolia } from 'viem/chains'; const pub = createPublicClient({ chain: sepolia, transport: http() }); const count = await pub.readContract({ address: ADDR, abi, functionName: 'count' }); const wallet = createWalletClient({ chain: sepolia, transport: custom(window.ethereum) }); const [account] = await wallet.requestAddresses(); const hash = await wallet.writeContract({ address: ADDR, abi, functionName: 'increment', account }); await pub.waitForTransactionReceipt({ hash });
35

What are the basic Foundry commands to create, build, test and work with a project?

Save to ▾
Show answer
curl -L https://foundry.paradigm.xyz | bash && foundryup forge init my-dapp # new project with src, test, script forge install OpenZeppelin/openzeppelin-contracts forge build # compile forge test -vvv # run tests with traces forge coverage # coverage report forge snapshot # gas snapshot anvil # local node cast call ADDR 'count()(uint256)' --rpc-url $RPC Foundry tests are written in Solidity and run fast; Hardhat is the JavaScript or TypeScript alternative with a large plugin ecosystem.
36

Write a Foundry deployment script.

Save to ▾
Show answer
// script/Deploy.s.sol pragma solidity ^0.8.24; import {Script, console} from 'forge-std/Script.sol'; import {Counter} from '../src/Counter.sol'; contract Deploy is Script { function run() external returns (Counter c) { vm.startBroadcast(); c = new Counter(); vm.stopBroadcast(); console.log('Counter deployed at', address(c)); } } # Run it with an encrypted keystore account forge script script/Deploy.s.sol --rpc-url $RPC_URL \ --account deployer --broadcast --verify Broadcast output in the broadcast folder records addresses for later scripts.
37

How do you store an NFT image on IPFS and use it in your contract?

Save to ▾
Show answer
Upload the image to IPFS using a node or a pinning service, which returns a CID. Create a metadata JSON file whose image field is ipfs://<imageCID>, then upload the metadata folder to get a folder CID. Set the contract's base URI to ipfs://<folderCID>/ so tokenURI(5) resolves to the file for token 5. Pin the content with more than one provider, and use a gateway URL only for display in the front-end.
38

How do you test against real mainnet contracts using a fork?

Save to ▾
Show answer
Anvil or Foundry tests can fork a live chain at a block, so you interact with real tokens and protocols locally. # Start a local fork anvil --fork-url $MAINNET_RPC --fork-block-number 21000000 # Or fork inside a test function setUp() public { vm.createSelectFork(vm.envString('MAINNET_RPC'), 21000000); } # Give yourself tokens or impersonate a whale deal(address(usdc), alice, 1_000e6); vm.prank(whale); Pinning the block number keeps results reproducible and makes RPC caching effective.
39

How do you verify a deployed contract's source code on a block explorer?

Save to ▾
Show answer
Verification uploads source and compiler settings so the explorer can recompile and match the bytecode, letting users read the code. # Foundry, using an explorer API key forge verify-contract 0xDeployedAddr src/Counter.sol:Counter \ --chain sepolia --etherscan-api-key $KEY --watch # With constructor arguments --constructor-args $(cast abi-encode 'constructor(address)' 0xOwner) # Hardhat npx hardhat verify --network sepolia 0xDeployedAddr 0xOwner Compiler version, optimiser runs and via-IR settings must match exactly.
40

How would you implement Sign-In with Ethereum on a web back-end?

Save to ▾
Show answer
Follow EIP-4361. The server generates a random nonce and stores it in the session. The front-end builds a SIWE message with domain, address, statement, URI, chain ID, nonce and issued-at time, and the wallet signs it. The server verifies the signature with a SIWE library, checks domain, nonce, expiry and chain, then issues a session cookie or JWT and deletes the nonce. For smart contract wallets, verify via ERC-1271 isValidSignature.
41

How do you handle a user on the wrong network in your dApp?

Save to ▾
Show answer
Check chainId after connecting and listen for chainChanged. Then ask the wallet to switch, and add the chain if it is unknown. const target = '0xaa36a7'; // Sepolia 11155111 try { await window.ethereum.request({ method: 'wallet_switchEthereumChain', params: [{ chainId: target }] }); } catch (e) { if (e.code === 4902) { await window.ethereum.request({ method: 'wallet_addEthereumChain', params: [{ chainId: target, chainName: 'Sepolia', rpcUrls: [RPC], nativeCurrency: { name: 'ETH', symbol: 'ETH', decimals: 18 } }] }); } } Disable write buttons until the network is correct.

Frequently asked questions

Why are practical questions important?

Most technical rounds include at least one live task. Practising the exact typing and reasoning makes you calm and fast in the real round.

How should I answer them?

Talk while you work: say your approach first, write the simplest correct version, then improve it and mention edge cases.