Coding Questions Archives - HackerRank Blog https://sandbox.hackerrank.com/blog/tag/coding-questions/ Leading the Skills-Based Hiring Revolution Thu, 31 Aug 2023 18:17:14 +0000 en-US hourly 1 https://wordpress.org/?v=6.7.1 https://www.hackerrank.com/blog/wp-content/uploads/hackerrank_cursor_favicon_480px-150x150.png Coding Questions Archives - HackerRank Blog https://sandbox.hackerrank.com/blog/tag/coding-questions/ 32 32 6 REST API Interview Questions Every Developer Should Know https://www.hackerrank.com/blog/rest-api-interview-questions-every-developer-should-know/ https://www.hackerrank.com/blog/rest-api-interview-questions-every-developer-should-know/#respond Thu, 07 Sep 2023 12:45:29 +0000 https://www.hackerrank.com/blog/?p=19091 APIs — or application programming interfaces — play a key role in the software ecosystem....

The post 6 REST API Interview Questions Every Developer Should Know appeared first on HackerRank Blog.

]]>
Abstract, futuristic image generated by AI

APIs — or application programming interfaces — play a key role in the software ecosystem. In a tech world that hinges on its interconnectedness, APIs serve as the vital middlemen that enable different pieces of software to work together seamlessly. And in the realm of APIs, REST (Representational State Transfer) stands as one of the most popular architectures. Why? Because it’s simple, scalable, and can handle multiple types of calls, return different data formats, and even change structurally with the correct implementation of hypermedia.

Given the ubiquitous role of REST APIs in modern software development, it’s not an overstatement to say that strong REST API skills are a must-have for developers across various disciplines — from full-stack and back-end developers to data scientists. But let’s not forget the recruiters and hiring managers striving to find the best talent. Knowing what questions to ask and what tasks to set during a technical interview can make a world of difference in finding the right hire.

In this blog post, we’re going to delve into what a REST API is, look at what you can expect from a REST API interview, and provide some challenging coding questions aimed at testing a developer’s REST API expertise. Whether you’re a developer looking to prepare for your next interview or a recruiter aiming to assess candidates proficiently, this post aims to be your go-to guide.

What is a REST API?

REST, short for representational state transfer, is an architectural style that sets the standard for creating web services. A REST API, therefore, is a set of conventions and rules for building and interacting with those services. 

The key components that define this architectural style include:

  • Resources: In REST, you interact with resources, which are essentially objects like users, products, or orders, represented as URLs or endpoints.
  • HTTP Methods: These resources are manipulated using standard HTTP methods. You’ve got GET for reading, POST for creating, PUT for updating, and DELETE for, well, deleting.
  • Stateless Interactions: REST APIs operate on a stateless basis. Every API request from a client to a server must contain all the information needed to process the request. This is one of the reasons why REST APIs are so scalable.

Simplicity, scalability, and versatility are hallmarks of REST APIs — and are some of the key reasons why this API protocol is so popular. REST APIs employ straightforward HTTP methods, are built to scale, and can return data in various formats (most commonly JSON and XML). With such attributes, plus strong community and library support, REST APIs have become the crucial connective tissue linking different services, applications, and systems in an increasingly integrated tech world.

What a REST API Interview Looks Like

When you’re sitting down for a REST API interview — either as a candidate eager to showcase your skills or as a member of a hiring team aiming to discover top talent — know that the focus will go beyond basic programming. You’ll explore the depths of HTTP methods, status codes, API endpoints, and the intricacies of data manipulation and retrieval. Understanding REST isn’t just about knowing the syntax; it’s about grasping the architecture, the philosophy, and the best practices that guide efficient API design and usage.

In this context, you may be asked to handle a variety of challenges:

  • Conceptual discussions about REST principles to gauge your foundational knowledge.
  • Hands-on coding tasks that require you to implement specific API calls, perhaps even integrating third-party services.
  • Debugging exercises where you’re given pieces of a RESTful service and asked to identify issues or optimize performance.
  • Scenarios where you have to design RESTful routes and resources, showcasing your understanding of RESTful best practices.

So who needs to be proficient in REST APIs? Well, you’d be hard-pressed to find a technical role that doesn’t benefit from REST API skills. However, they’re particularly essential for:

  • Back-End Developers: The architects behind the server-side logic, often responsible for setting up the API endpoints.
  • Full-Stack Developers: The jacks-of-all-trades who need to know both client-side and server-side technologies, including APIs.
  • API Developers: Those specializing in API development, obviously.
  • Data Scientists and Engineers: Professionals who need to pull in data from various services for analytics and data processing.
  • Mobile App Developers: Many mobile apps pull from web services, often using REST APIs.
  • QA Engineers: Those responsible for testing the reliability and scalability of web services, including APIs.

1. Create a Simple RESTful Service to Manage a To-Do List

This question serves as a foundational task to assess your grasp of REST API basics, CRUD operations, and endpoint creation.

Task: Write a Python function using the Flask framework to manage a simple to-do list. Your API should support the following operations: adding a new task, getting a list of all tasks, updating a task description, and deleting a task.

Input Format: For adding a new task, the input should be a JSON object like `{“task”: “Buy groceries”}`.

Constraints:

  • The task description will be a non-empty string.
  • Each task will have a unique identifier.

Output Format: The output should also be in JSON format. For fetching all tasks, the output should look like `[{“id”: 1, “task”: “Buy groceries”}, {“id”: 2, “task”: “Read a book”}]`.

Sample Code:

from flask import Flask, jsonify, request

app = Flask(__name__)

tasks = []

task_id = 1

@app.route('/tasks', methods=['GET'])

def get_tasks():

    return jsonify(tasks)

@app.route('/tasks', methods=['POST'])

def add_task():

    global task_id

    new_task = {"id": task_id, "task": request.json['task']}

    tasks.append(new_task)

    task_id += 1

    return jsonify(new_task), 201

@app.route('/tasks/<int:id>', methods=['PUT'])

def update_task(id):

    task = next((item for item in tasks if item['id'] == id), None)

    if task is None:

        return jsonify({"error": "Task not found"}), 404

    task['task'] = request.json['task']

    return jsonify(task)

@app.route('/tasks/<int:id>', methods=['DELETE'])

def delete_task(id):

    global tasks

    tasks = [task for task in tasks if task['id'] != id]

    return jsonify({"result": "Task deleted"})

Explanation:  

The Python code uses Flask to set up a simple RESTful API. It has four endpoints corresponding to CRUD operations for managing tasks. `GET` fetches all tasks, `POST` adds a new task, `PUT` updates a task based on its ID, and `DELETE` removes a task by its ID.

2. Implement Pagination in a REST API

This question is designed to gauge your understanding of pagination, a technique often used in REST APIs to manage large sets of data.

Task: Modify the previous Python Flask API for managing tasks to include pagination. The API should return a subset of tasks based on `limit` and `offset` query parameters.

Input Format: For fetching tasks, the API URL could look like `/tasks?offset=2&limit=3`.

Constraints:

  • The `offset` will be a non-negative integer.
  • The `limit` will be a positive integer.

Output Format:  

The output should be in JSON format, returning tasks based on the given `offset` and `limit`.

Sample Code:

@app.route('/tasks', methods=['GET'])

def get_tasks():

    offset = int(request.args.get('offset', 0))

    limit = int(request.args.get('limit', len(tasks)))

    paginated_tasks = tasks[offset:offset+limit]

    return jsonify(paginated_tasks)

Explanation:  

In this modification, the `get_tasks` function now uses the `offset` and `limit` query parameters to slice the `tasks` list. This way, it only returns a subset of tasks based on those parameters. It’s a simple yet effective way to implement pagination in a REST API.

Explore verified tech roles & skills.

The definitive directory of tech roles, backed by machine learning and skills intelligence.

Explore all roles

3. Implement Basic Authentication

Authentication is crucial in APIs to ensure only authorized users can perform certain actions. This question tests your knowledge of implementing basic authentication in a REST API.

Task: Modify the previous Flask API for managing tasks to require basic authentication for all operations except retrieving the list of tasks (`GET` method).

Input Format: API requests should include basic authentication headers.

Constraints: For simplicity, assume a single user with a username of “admin” and a password of “password.”

Output Format: Unauthorized requests should return a 401 status code. Otherwise, the API behaves as in previous examples.

Sample Code:

from flask import Flask, jsonify, request, abort

from functools import wraps

app = Flask(__name__)

# ... (previous code for task management)

def check_auth(username, password):

    return username == 'admin' and password == 'password'

def requires_auth(f):

    @wraps(f)

    def decorated(*args, **kwargs):

        auth = request.authorization

        if not auth or not check_auth(auth.username, auth.password):

            abort(401)

        return f(*args, **kwargs)

    return decorated

@app.route('/tasks', methods=['POST', 'PUT', 'DELETE'])

@requires_auth

def manage_tasks():

    # ... (previous code for POST, PUT, DELETE methods)

Explanation:  

In this example, the `requires_auth` decorator function checks for basic authentication in incoming requests. The `check_auth` function simply validates the username and password. If the credentials are incorrect or missing, the server returns a 401 status code. This decorator is applied to routes requiring authentication (`POST`, `PUT`, `DELETE`).

4. Implement Rate Limiting

Rate limiting is used to control the amount of incoming requests to a server. This question evaluates your understanding of how to set up rate limiting in a RESTful service.

Task: Add rate limiting to your Flask API for managing tasks. Limit each client to 10 requests per minute for any type of operation.

Input Format: Standard API requests, same as previous examples.

Constraints: Rate limiting should apply per client IP address.

Output Format: Clients exceeding the rate limit should receive a 429 status code and the message “Too many requests.”

Sample Code:

from flask import Flask, jsonify, request, abort, make_response

from time import time

from functools import wraps

app = Flask(__name__)

client_times = {}

def rate_limit(f):

    @wraps(f)

    def decorated(*args, **kwargs):

        client_ip = request.remote_addr

        current_time = int(time())
    
        requests = client_times.get(client_ip, [])       

        # Filter requests in the last minute

        requests = [req_time for req_time in requests if current_time - req_time < 60]

        if len(requests) >= 10:

            return make_response(jsonify({"error": "Too many requests"}), 429)
       
        requests.append(current_time)

        client_times[client_ip] = requests
       
        return f(*args, **kwargs)
   
    return decorated

@app.route('/tasks', methods=['GET', 'POST', 'PUT', 'DELETE'])

@rate_limit

def manage_tasks():

    # ... (previous code for GET, POST, PUT, DELETE methods)

Explanation:  

The `rate_limit` decorator function checks how many times a client has made a request within the last minute. It uses a global `client_times` dictionary to keep track of these request times, keyed by client IP. If a client exceeds 10 requests, a 429 status code (“Too many requests”) is returned.

5. Implement API Versioning

When APIs evolve, maintaining different versions ensures older clients aren’t broken by new updates. This question tests your skills in implementing versioning in a RESTful service.

Task: Extend your Flask API for task management to support both a `v1` and a `v2` version. In `v2`, the task object should include an additional field called `status`.

Input Format: The version of the API should be specified in the URL, like `/v1/tasks` and `/v2/tasks`.

Constraints: The `status` field in `v2` is a string and can have values “pending,” “completed,” or “archived.”

Output Format: For `v1`, the task object remains the same as before. For `v2`, it should include the `status` field.

Sample Code:

from flask import Flask, jsonify, request

app = Flask(__name__)

tasks_v1 = []

tasks_v2 = []

task_id = 1

@app.route('/v1/tasks', methods=['GET', 'POST'])

def manage_tasks_v1():

    global task_id

    # ... (previous code for v1)

    return jsonify(tasks_v1)

@app.route('/v2/tasks', methods=['GET', 'POST'])

def manage_tasks_v2():

    global task_id

    if request.method == 'POST':

        new_task = {"id": task_id, "task": request.json['task'], "status": "pending"}

        tasks_v2.append(new_task)

        task_id += 1

        return jsonify(new_task)

    return jsonify(tasks_v2)

Explanation:  

The code includes two routes for task management, `/v1/tasks` and `/v2/tasks`. The `v1` route behaves as in previous examples. The `v2` route includes an additional `status` field in the task object, initialized to “pending” when a new task is added.

6. Custom HTTP Status Codes and Error Handling

Proper error handling and status codes make an API user-friendly and easier to debug. This question targets your knowledge of using appropriate HTTP status codes for various scenarios.

Task: Update your Flask API to return custom error messages along with appropriate HTTP status codes for different error scenarios.

Input Format: Standard API requests, same as previous examples.

Constraints:

  • Return a 404 status code with a custom message if a task is not found.
  • Return a 400 status code with a custom message if the input payload is missing necessary fields.

Output Format: The API should return JSON-formatted error messages along with appropriate HTTP status codes.

Sample Code:

from flask import Flask, jsonify, request, make_response

app = Flask(__name__)

tasks = []

@app.route('/tasks/<int:task_id>', methods=['GET', 'PUT', 'DELETE'])

def manage_single_task(task_id):

    task = next((item for item in tasks if item['id'] == task_id), None)

    if task is None:

        return make_response(jsonify({"error": "Task not found"}), 404)      

    if request.method == 'PUT':

        if 'task' not in request.json:

            return make_response(jsonify({"error": "Missing fields in request"}), 400)       

        task['task'] = request.json['task']

        return jsonify(task)

    # ... (previous code for GET and DELETE methods)

Explanation:  

In this example, the `manage_single_task` function first checks if the task exists. If not, it returns a 404 status code with a custom error message. If the task exists and it’s a `PUT` request but missing the ‘task’ field, it returns a 400 status code with another custom error message.

Resources to Improve REST API Knowledge

This article was written with the help of AI. Can you tell which parts?

The post 6 REST API Interview Questions Every Developer Should Know appeared first on HackerRank Blog.

]]>
https://www.hackerrank.com/blog/rest-api-interview-questions-every-developer-should-know/feed/ 0
6 Azure Interview Questions Every Developer Should Know https://www.hackerrank.com/blog/azure-interview-questions-every-developer-should-know/ https://www.hackerrank.com/blog/azure-interview-questions-every-developer-should-know/#respond Wed, 30 Aug 2023 13:25:59 +0000 https://www.hackerrank.com/blog/?p=19068 Cloud technology is far more than just an industry buzzword these days; it’s the backbone...

The post 6 Azure Interview Questions Every Developer Should Know appeared first on HackerRank Blog.

]]>
Abstract, futuristic image generated by AI

Cloud technology is far more than just an industry buzzword these days; it’s the backbone of modern IT infrastructures. And among the crowded field of cloud service providers, a handful of tech companies have emerged as key players. Microsoft’s Azure, with its enormous range of services and capabilities, has solidified its position in this global market, rivaling giants like AWS and Google Cloud and quickly becoming a favorite among both businesses and developers at the forefront of cloud-based innovation. 

As Azure continues to expand its footprint across industries, the demand for professionals proficient in its ecosystem is growing too. As a result, interviews that dive deep into Azure skills are becoming more common — and for a good reason. These interviews don’t just test a candidate’s knowledge; they probe for hands-on experience and the ability to leverage Azure’s powerful features in real-world scenarios.

Whether you’re a developer eyeing a role in this domain or a recruiter seeking to better understand the technical nuances of Azure, it can be helpful to delve into questions that capture the essence of Azure’s capabilities and potential challenges. In this guide, we unravel what Azure really is, the foundations of an Azure interview, and of course, a curated set of coding questions that every Azure aficionado should be prepared to tackle.

What is Azure?

Azure is Microsoft’s answer to cloud computing — but it’s also much more than that. It’s a vast universe of interconnected services and tools designed to meet a myriad of IT needs, from the basic to the complex.

More than just a platform, Azure offers Infrastructure-as-a-Service (IaaS), providing essential resources like virtual machines and networking. It delves into Platform-as-a-Service (PaaS), where services such as Azure App Service or Azure Functions let you deploy applications without getting bogged down by infrastructure concerns. And it has software-as-a-Service (SaaS) offerings like Office 365 and Dynamics 365.

Yet, Azure’s capabilities don’t end with these three service models. It boasts specialized services for cutting-edge technologies like IoT, AI, and machine learning. From building an intelligent bot to managing a fleet of IoT devices, Azure has tools and services tailor-made for these ventures.

What an Azure Interview Looks Like

An interview focused on Azure isn’t just a test of your cloud knowledge; it’s an exploration of your expertise in harnessing the myriad services and tools that Azure offers. Given the platform’s vast expanse, the interview could span a range of topics. It could probe your understanding of deploying and configuring resources using the Azure CLI or ARM templates. Or it might assess your familiarity with storage solutions like Blob, Table, Queue, and the more recent Cosmos DB. Networking in Azure, with its virtual networks, VPNs, and Traffic Manager, is another crucial area that interviewers often touch upon. And with the increasing emphasis on real-time data and AI, expect a deep dive into Azure’s data and AI services, like machine learning or Stream Analytics.

While the nature of questions can vary widely based on the specific role, there are some common threads. Interviewers often look for hands-on experience, problem-solving ability, and a sound understanding of best practices and architectural designs within the Azure ecosystem. For instance, if you’re aiming for a role like an Azure solutions architect, expect scenarios that challenge your skills in designing scalable, resilient, and secure solutions on Azure. On the other hand, Azure DevOps engineers might find themselves solving automation puzzles, ensuring smooth CI/CD pipelines, or optimizing infrastructure as code.

But it’s not all technical! Given that Azure is often pivotal in business solutions, you might also be tested on your ability to align Azure’s capabilities with business goals, cost management, or even disaster recovery strategies.

1. Deploy a Web App Using Azure CLI

The Azure command-line interface (CLI) is an essential tool for developers and administrators to manage Azure resources. This question tests a candidate’s proficiency with Azure CLI commands, specifically focusing on deploying web applications to Azure.

Task: Write an Azure CLI script to deploy a simple web app using Azure App Service. The script should create the necessary resources, deploy a sample HTML file, and return the public URL of the web app.

Input Format: The script should accept the following parameters:

  • Resource group name
  • Location (e.g., “East U.S.”)
  • App service plan name
  • Web app name

Constraints:

  • The web app should be hosted on a free tier App Service plan.
  • The HTML file to be deployed should simply display “Hello Azure!”

Output Format: The script should print the public URL of the deployed web app.

Sample Code:

#!/bin/bash

# Parameters

resourceGroupName=$1

location=$2

appServicePlanName=$3

webAppName=$4

# Create a resource group

az group create --name $resourceGroupName --location $location

# Create an App Service plan on Free tier

az appservice plan create --name $appServicePlanName --resource-group $resourceGroupName --sku F1 --is-linux

# Create a web app

az webapp create --name $webAppName --resource-group $resourceGroupName --plan $appServicePlanName --runtime "NODE|14-lts"

# Deploy sample HTML file

echo "<html><body><h1>Hello Azure!</h1></body></html>" > index.html

az webapp up --resource-group $resourceGroupName --name $webAppName --html

# Print the public URL

echo "Web app deployed at: https://$webAppName.azurewebsites.net"

Explanation:

The script begins by creating a resource group using the provided name and location. It then creates an App Service plan on the free tier. Subsequently, a web app is created using Node.js as its runtime (although we’re deploying an HTML file, the runtime is still needed). A sample HTML file is then generated on the fly with the content “Hello Azure!” and deployed to the web app using `az webapp up`. Finally, the public URL of the deployed app is printed.

2. Configure Azure Blob Storage and Upload a File

Azure Blob Storage is a vital service in the Azure ecosystem, allowing users to store vast amounts of unstructured data. This question examines a developer’s understanding of Blob Storage and their proficiency in interacting with it programmatically.

Task: Write a Python script using Azure SDK to create a container in Azure Blob Storage, and then upload a file to this container.

Input Format: The script should accept the following parameters:

  • Connection string
  • Container name
  • File path (of the file to be uploaded)

Constraints:

  • Ensure the container’s access level is set to “Blob” (meaning the blobs/files can be accessed, but not the container’s metadata or file listing).
  • Handle potential exceptions gracefully, like invalid connection strings or file paths.

Output Format: The script should print the URL of the uploaded blob.

Sample Code:

from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient

def upload_to_blob(connection_string, container_name, file_path):

    try:
        # Create the BlobServiceClient

        blob_service_client = BlobServiceClient.from_connection_string(connection_string)

        # Create or get container

        container_client = blob_service_client.get_container_client(container_name)

        if not container_client.exists():

            blob_service_client.create_container(container_name, public_access='blob')

        # Upload file to blob

        blob_client = blob_service_client.get_blob_client(container=container_name, blob=file_path.split('/')[-1])

        with open(file_path, "rb") as data:

            blob_client.upload_blob(data)

        print(f"File uploaded to: {blob_client.url}")     

    except Exception as e:

        print(f"An error occurred: {e}")
# Sample Usage

# upload_to_blob('<Your Connection String>', 'sample-container', 'path/to/file.txt')

Explanation:

The script uses the Azure SDK for Python. After establishing a connection with the Blob service using the provided connection string, it checks if the specified container exists. If not, it creates one with the access level set to “Blob.” The file specified in the `file_path` is then read as binary data and uploaded to the blob storage. Once the upload is successful, the URL of the blob is printed. Any exceptions encountered during these operations are caught and printed to inform the user of potential issues.

Explore verified tech roles & skills.

The definitive directory of tech roles, backed by machine learning and skills intelligence.

Explore all roles

3. Azure Functions: HTTP Trigger with Cosmos DB Integration

Azure Functions, known for its serverless compute capabilities, allows developers to run code in response to specific events. Cosmos DB, on the other hand, is a multi-model database service for large-scale applications. This question assesses a developer’s ability to create an Azure Function triggered by an HTTP request and integrate it with Cosmos DB.

Task: Write an Azure Function that’s triggered by an HTTP GET request. The function should retrieve a document from an Azure Cosmos DB based on a provided ID and return the document as a JSON response.

Input Format: The function should accept an HTTP GET request with a query parameter named `docId`, representing the ID of the desired document.

Output Format: The function should return the requested document in JSON format or an error message if the document isn’t found.

Constraints:

  • Use the Azure Functions 3.x runtime.
  • The Cosmos DB has a database named `MyDatabase` and a container named `MyContainer`.
  • Handle exceptions gracefully, ensuring proper HTTP response codes and messages.

Sample Code:

using System.IO;

using Microsoft.AspNetCore.Mvc;

using Microsoft.Azure.WebJobs;

using Microsoft.Azure.WebJobs.Extensions.Http;

using Microsoft.AspNetCore.Http;

using Microsoft.Extensions.Logging;

using Newtonsoft.Json;

using Microsoft.Azure.Documents.Client;

using Microsoft.Azure.Documents.Linq;

using System.Linq;

public static class GetDocumentFunction

{

    [FunctionName("RetrieveDocument")]

    public static IActionResult Run(

        [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req,

        [CosmosDB(

            databaseName: "MyDatabase",

            collectionName: "MyContainer",

            ConnectionStringSetting = "AzureWebJobsCosmosDBConnectionString",

            Id = "{Query.docId}")] dynamic document,

        ILogger log)

    {

        log.LogInformation("C# HTTP trigger function processed a request.");

        if (document == null)

        {

            return new NotFoundObjectResult("Document not found.");

        }

        return new OkObjectResult(document);
    }
}

Explanation:

This Azure Function uses the Azure Functions 3.x runtime and is written in C#. It’s triggered by an HTTP GET request. The function leverages the CosmosDB binding to fetch a document from Cosmos DB using the provided `docId` query parameter. If the document exists, it’s returned as a JSON response. Otherwise, a 404 Not Found response is returned with an appropriate error message.

Note: This code assumes the Cosmos DB connection string is stored in an application setting named “AzureWebJobsCosmosDBConnectionString.”

4. Azure Virtual Machine: Automate VM Setup with Azure SDK for Python**

Azure Virtual Machines (VMs) are a fundamental building block in the Azure ecosystem. It’s crucial for developers to know how to automate VM creation and setup to streamline operations and ensure standardized configurations. This question assesses a developer’s understanding of the Azure SDK for Python and their ability to automate VM provisioning.

Task: Write a Python script using the Azure SDK to create a new virtual machine. The VM should run Ubuntu Server 18.04 LTS, and once set up, it should automatically install Docker.

Input Format: The script should accept the following parameters:

  • Resource group name
  • VM name
  • Location (e.g., “East U.S.”)
  • Azure subscription ID
  • Client ID (for Azure service principal)
  • Client secret (for Azure service principal)
  • Tenant ID (for Azure service principal)

Constraints:

  • Ensure the VM is of size `Standard_DS1_v2`.
  • Set up the VM to use SSH key authentication.
  • Assume the SSH public key is located at `~/.ssh/id_rsa.pub`.
  • Handle exceptions gracefully.

Output Format: The script should print the public IP address of the created VM.

Sample Code:

from azure.identity import ClientSecretCredential

from azure.mgmt.compute import ComputeManagementClient

from azure.mgmt.network import NetworkManagementClient

from azure.mgmt.resource import ResourceManagementClient




def create_vm_with_docker(resource_group, vm_name, location, subscription_id, client_id, client_secret, tenant_id):

    # Authenticate using service principal

    credential = ClientSecretCredential(client_id=client_id, client_secret=client_secret, tenant_id=tenant_id)

    # Initialize management clients

    resource_client = ResourceManagementClient(credential, subscription_id)

    compute_client = ComputeManagementClient(credential, subscription_id)

    network_client = NetworkManagementClient(credential, subscription_id)

    # Assuming network setup, storage, etc. are in place

    # Fetch SSH public key

    with open("~/.ssh/id_rsa.pub", "r") as f:

        ssh_key = f.read().strip()

    # Define the VM parameters, including post-deployment script to install Docker

    vm_parameters = {

        #... (various VM parameters like size, OS type, etc.)

        'osProfile': {

            'computerName': vm_name,

            'adminUsername': 'azureuser',

            'linuxConfiguration': {

                'disablePasswordAuthentication': True,

                'ssh': {

                    'publicKeys': [{

                        'path': '/home/azureuser/.ssh/authorized_keys',

                        'keyData': ssh_key

                    }]

                }

            },

            'customData': "IyEvYmluL2Jhc2gKc3VkbyBhcHQtZ2V0IHVwZGF0ZSAmJiBzdWRvIGFwdC1nZXQgaW5zdGFsbCAt

            eSBkb2NrZXIuY2U="  # This is base64 encoded script for "sudo apt-get update && sudo apt-get install -y docker.ce"

        }

    }

    # Create VM

    creation_poller = compute_client.virtual_machines.create_or_update(resource_group, vm_name, vm_parameters)

    creation_poller.result()

    # Print the public IP address (assuming IP is already allocated)

    public_ip = network_client.public_ip_addresses.get(resource_group, f"{vm_name}-ip")

    print(f"Virtual Machine available at: {public_ip.ip_address}")

# Sample Usage (with parameters replaced appropriately)

# create_vm_with_docker(...)

Explanation:

The script begins by establishing authentication using the provided service principal credentials. It initializes management clients for resource, compute, and networking operations. After setting up networking and storage (which are assumed to be in place for brevity), the VM is defined with the necessary parameters. The post-deployment script installs Docker on the VM upon its first boot. Once the VM is created, its public IP address is printed.

Note: The Docker installation script is base64 encoded for brevity. In real use cases, you might use cloud-init or other provisioning tools for more complex setups.

5. Azure SQL Database: Data Migration and Querying

Azure SQL Database is a fully managed relational cloud database service for developers. The integration between applications and data becomes crucial, especially when migrating data or optimizing application performance through SQL queries.

Task: Write a Python script that does the following:

  1. Connects to an Azure SQL Database using provided connection details
  2. Migrates data from a CSV file into a table in the Azure SQL Database
  3. Runs a query on the table to fetch data based on specific criteria

Input Format: The script should accept command line arguments in the following order:

  • Connection string for the Azure SQL Database
  • Path to the CSV file
  • The query to run on the table

Constraints:

  • The CSV file will have headers that match the column names of the target table.
  • Handle exceptions gracefully, such as failed database connections, invalid SQL statements, or CSV parsing errors.

Output Format: The script should print:

  • A success message after data has been migrated
  • The results of the SQL query in a readable format

Sample Code:

import pyodbc

import csv

import sys

def migrate_and_query_data(conn_string, csv_path, sql_query):

    try:

        # Connect to Azure SQL Database

        conn = pyodbc.connect(conn_string)

        cursor = conn.cursor()

        # Migrate CSV data

        with open(csv_path, 'r') as file:

            reader = csv.DictReader(file)

            for row in reader:

                columns = ', '.join(row.keys())

                placeholders = ', '.join('?' for _ in row)

                query = f"INSERT INTO target_table ({columns}) VALUES ({placeholders})"

                cursor.execute(query, list(row.values()))

        print("Data migration successful!")

        # Execute SQL query and display results

        cursor.execute(sql_query)

        for row in cursor.fetchall():

            print(row)

        conn.close()

    except pyodbc.Error as e:

        print(f"Database error: {e}")

    except Exception as e:

        print(f"An error occurred: {e}")

# Sample usage (with parameters replaced appropriately)

# migrate_and_query_data(sys.argv[1], sys.argv[2], sys.argv[3])

Explanation: 

This script utilizes the `pyodbc` library to interact with Azure SQL Database. The script starts by establishing a connection to the database and then iterates through the CSV rows to insert them into the target table. After the data migration, it runs the provided SQL query and displays the results. The script ensures that database-related errors, as well as other exceptions, are captured and presented to the user.

Note: Before running this, you’d need to install the necessary Python packages, such as `pyodbc` and ensure the right drivers for Azure SQL Database are in place.

6. Azure Logic Apps with ARM Templates: Automated Data Sync

Azure Logic Apps provide a powerful serverless framework to integrate services and automate workflows. While the Azure Portal offers a user-friendly visual designer, in professional settings, especially with DevOps and CI/CD pipelines, there’s often a need to define these workflows in a more programmatic way. Enter ARM (Azure Resource Manager) templates: a declarative syntax to describe resources and configurations, ensuring idempotent deployments across environments.

Task: Taking it up a notch from the visual designer, your challenge is to implement an Azure Logic App that automates the process of syncing data between two Azure Table Storage accounts using an ARM template. This will test both your familiarity with the Logic Apps service and your ability to translate a workflow into an ARM template.

Inputs:

  • Source Azure Table Storage connection details
  • Destination Azure Table Storage connection details

Constraints:

  • Your ARM template should define the Logic App, its trigger, actions, and any associated resources like connectors.
  • The Logic App should be triggered whenever a new row is added to the source Azure Table Storage.
  • Newly added rows should be replicated to the destination Azure Table Storage without any data loss or duplication.
  • Any failures in data transfer should be logged appropriately.

Sample ARM Template (simplified for brevity):

{

    "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",

    "contentVersion": "1.0.0.0",

    "resources": [

        {

            "type": "Microsoft.Logic/workflows",

            "apiVersion": "2017-07-01",

            "name": "SyncAzureTablesLogicApp",

            "location": "[resourceGroup().location]",

            "properties": {

                "definition": {

                    "$schema": "...",

                    "contentVersion": "...",

                    "triggers": {

                        "When_item_is_added": {

                            "type": "ApiConnection",

                            ...

                        }

                    },

                    "actions": {

                        "Add_item_to_destination": {

                            "type": "ApiConnection",

                            ...

                        }

                    }

                },

                "parameters": { ... }

            }

        }

    ],

    "outputs": { ... }

}

Explanation:

Using ARM templates to define Azure Logic Apps provides a programmatic and version-controllable approach to designing cloud workflows. The provided ARM template is a basic structure, defining a Logic App resource and its corresponding trigger and action for syncing data between two Azure Table Storage accounts. While the ARM template in this question is simplified, a proficient Azure developer should be able to flesh out the necessary details.

To implement the full solution, candidates would need to detail the trigger for detecting new rows in the source table, the action for adding rows to the destination table, and the error-handling logic.

Resources to Improve Azure Knowledge

This article was written with the help of AI. Can you tell which parts?

The post 6 Azure Interview Questions Every Developer Should Know appeared first on HackerRank Blog.

]]>
https://www.hackerrank.com/blog/azure-interview-questions-every-developer-should-know/feed/ 0
7 Android Interview Questions Every Developer Should Know https://www.hackerrank.com/blog/android-interview-questions-every-developer-should-know/ https://www.hackerrank.com/blog/android-interview-questions-every-developer-should-know/#respond Thu, 17 Aug 2023 12:45:01 +0000 https://www.hackerrank.com/blog/?p=19056 In a world now dominated by smartphones and wearables, Android stands as a titan, powering...

The post 7 Android Interview Questions Every Developer Should Know appeared first on HackerRank Blog.

]]>
Abstract, futuristic image generated by AI

In a world now dominated by smartphones and wearables, Android stands as a titan, powering billions of devices and shaping the mobile tech landscape. From budget phones to luxury devices, from smartwatches to TVs, Android’s versatility and adaptability have made it the OS of choice for countless manufacturers and developers. It’s no surprise, then, that Android development skills are in high demand

But with great demand comes some competition. To stand out, Android developers will need to be intimately familiar with the platform’s intricacies and challenges. And what better way to demonstrate that expertise than through a technical interview? This guide is here to help developers prepare for their  mobile development interviews, and to arm hiring teams with the tools they need to identify their next hire.

What is Android?

Dive into any bustling city, and you’ll likely find a common sight: people engaged with their devices. Many of these devices — be it smartphones, tablets, watches, or even car dashboards — run on Android. But to truly appreciate its prominence, we must delve deeper.

Android is an open-source operating system, primarily designed for mobile devices. Birthed by Android Inc. and later acquired by Google in 2005, it’s built on top of the Linux kernel. While originally centered around a Java interface for app development, Android’s horizon expanded with the introduction of Kotlin, a modern alternative that’s fast becoming a favorite among developers.

Over the span of its existence, Android has undergone numerous evolutions. From its early days with dessert-themed code names like Cupcake and Pie to its recent, more functionally named updates, the OS has consistently pushed the envelope in innovation, security, and performance. 

What an Android Interview Looks Like

An Android coding interview often mirrors the complexities and nuances of the platform itself. Candidates might be presented with challenges ranging from designing efficient UI layouts that adapt to multiple screen sizes to ensuring seamless data synchronization in the background, all while maintaining optimal battery performance.

One fundamental area often tested is a developer’s grasp of the Android lifecycle. Understanding how different components (like activities or services) come to life, interact, and, perhaps more importantly, cease to exist, can be the key to crafting efficient and bug-free apps. Additionally, topics such as intents, broadcast receivers, and content providers frequently find their way into these discussions, highlighting the interconnected nature of Android apps and the system they operate within.

But it’s not all about coding. System design questions can pop up, gauging a developer’s ability to architect an app that’s scalable, maintainable, and user-friendly. Debugging skills, a critical asset for any developer, can also be under the spotlight, with interviewees sometimes having to identify, explain, and solve a piece of buggy code.

So, whether you’re a seasoned developer gearing up for your next role or a recruiter aiming to refine your interview process, remember that an Android interview is more than a test — it’s an opportunity. An opportunity to showcase expertise, to identify potential, and to ensure that as Android continues to evolve, so do the professionals driving its innovation.

1. Implement a Custom ListAdapter

One of the foundational skills for any Android developer is understanding how to display lists of data efficiently. The `ListView` and its successor, the `RecyclerView`, are commonly used components for this purpose. A custom `ListAdapter` or `RecyclerView.Adapter` lets you control the look and functionality of each item in the list.

Task: Create a simple `RecyclerView.Adapter` that displays a list of user names and their ages. Each item should show the name and age side by side.

Input Format: You will be given an ArrayList of User objects. Each User object has two fields: a `String` representing the user’s name and an `int` representing their age.

Constraints:

  • The list will contain between 1 and 1000 users.
  • Each user’s name will be non-empty and will have at most 100 characters.
  • Age will be between 0 and 120.

Output Format: The adapter should bind the data such that each item in the `RecyclerView` displays a user’s name and age side by side.

Sample Input:

“`java

ArrayList<User> users = new ArrayList<>();

users.add(new User(“Alice”, 28));

users.add(new User(“Bob”, 22));

Sample Code:

public class UserAdapter extends RecyclerView.Adapter<UserAdapter.UserViewHolder> {

    private ArrayList<User> users;

    public UserAdapter(ArrayList<User> users) {

        this.users = users;

    }

 

    @NonNull

    @Override

    public UserViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_item, parent, false);

        return new UserViewHolder(itemView);

    }

    @Override

    public void onBindViewHolder(@NonNull UserViewHolder holder, int position) {

        User currentUser = users.get(position);

        holder.nameTextView.setText(currentUser.getName());

        holder.ageTextView.setText(String.valueOf(currentUser.getAge()));

    }

    @Override

    public int getItemCount() {

        return users.size();

    }

    static class UserViewHolder extends RecyclerView.ViewHolder {

        TextView nameTextView;

        TextView ageTextView;

        public UserViewHolder(@NonNull View itemView) {

            super(itemView);

            nameTextView = itemView.findViewById(R.id.nameTextView);

            ageTextView = itemView.findViewById(R.id.ageTextView);

        }

    }

}

 

Explanation:

The `UserAdapter` extends the `RecyclerView.Adapter` class, defining a custom ViewHolder, `UserViewHolder`. This ViewHolder binds to the `nameTextView` and `ageTextView` in the user item layout.

In the `onBindViewHolder` method, the adapter fetches the current User object based on the position and sets the name and age to their respective TextViews. The `getItemCount` method simply returns the size of the users list, determining how many items the `RecyclerView` will display.

2. Manage Activity Lifecycle with Configuration Changes

The Android Activity Lifecycle is fundamental to creating apps that behave correctly across different user actions and system events. One common challenge is ensuring that during configuration changes, such as screen rotations, the app doesn’t lose user data and effectively preserves its current state.

Task: Implement the necessary methods in an Activity to handle configuration changes (like screen rotation) and preserve a counter. The Activity has a button that, when pressed, increments a counter. The current value of the counter should be displayed in a TextView and should not reset upon screen rotation.

Constraints:

  • The counter can range from 0 to a maximum of 1,000.
  • Only the screen rotation configuration change needs to be handled.

Output Format: The TextView should display the current counter value, updating every time the button is pressed. This value should persist across configuration changes.

Sample Code:

“`java

public class CounterActivity extends AppCompatActivity {

 

    private static final String COUNTER_KEY = “counter_key”;

    private int counter = 0;

    private TextView counterTextView;

    private Button incrementButton;

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_counter);

 

        counterTextView = findViewById(R.id.counterTextView);

        incrementButton = findViewById(R.id.incrementButton);

 

        if (savedInstanceState != null) {

            counter = savedInstanceState.getInt(COUNTER_KEY);

        }

 

        displayCounter();

 

        incrementButton.setOnClickListener(v -> {

            counter++;

            displayCounter();

        });

    }

 

    @Override

    protected void onSaveInstanceState(@NonNull Bundle outState) {

        super.onSaveInstanceState(outState);

        outState.putInt(COUNTER_KEY, counter);

    }

 

    private void displayCounter() {

        counterTextView.setText(String.valueOf(counter));

    }

}

 

Explanation:

This `CounterActivity` displays a counter that can be incremented with a button. The critical part is the `onSaveInstanceState` method, which is called before an Activity might be destroyed, like before a configuration change. In this method, we save the current counter value in the `Bundle` using the key `COUNTER_KEY`.

Then, in the `onCreate` method, which is called when the Activity is created or recreated (e.g., after a screen rotation), we check if there’s a saved instance state. If there is, it means the Activity is being recreated, and we restore the counter value from the `Bundle`. By doing this, we ensure that the counter value is preserved across configuration changes.

Explore verified tech roles & skills.

The definitive directory of tech roles, backed by machine learning and skills intelligence.

Explore all roles

3. Implement LiveData with ViewModel

The modern Android app architecture recommends using `ViewModel` and `LiveData` to build robust, maintainable, and testable apps. `LiveData` is an observable data holder class that respects the lifecycle of app components, ensuring that UI updates are made only when necessary and avoiding potential memory leaks.

Task: Create a `ViewModel` that holds a `LiveData` integer value representing a score. The ViewModel should have methods to increment and decrement the score. Implement an Activity that observes this `LiveData` and updates a TextView with the current score. The Activity should also have buttons to increase and decrease the score.

Input Format: Initial score starts at 0.

Constraints: The score can range between 0 and 100.

Output Format: The TextView in the Activity should display the current score, updating every time the increment or decrement buttons are pressed. This value should remain consistent across configuration changes.

Sample Code:

“`java

public class ScoreViewModel extends ViewModel {

    private MutableLiveData<Integer> score = new MutableLiveData<>(0);

    public LiveData<Integer> getScore() {

        return score;

    }

    public void incrementScore() {

        score.setValue(score.getValue() + 1);

    }

    public void decrementScore() {

        if (score.getValue() > 0) {

            score.setValue(score.getValue() – 1);

        }

    }

}

public class ScoreActivity extends AppCompatActivity {

    private ScoreViewModel viewModel;

    private TextView scoreTextView;

    private Button increaseButton, decreaseButton;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_score);

        viewModel = new ViewModelProvider(this).get(ScoreViewModel.class);

        scoreTextView = findViewById(R.id.scoreTextView);

        increaseButton = findViewById(R.id.increaseButton);

        decreaseButton = findViewById(R.id.decreaseButton);

        viewModel.getScore().observe(this, score -> scoreTextView.setText(String.valueOf(score)));

        increaseButton.setOnClickListener(v -> viewModel.incrementScore());

        decreaseButton.setOnClickListener(v -> viewModel.decrementScore());

    }

}

Explanation:

The `ScoreViewModel` class extends the `ViewModel` class and contains a `MutableLiveData` object representing the score. There are methods to get the score (which returns a non-modifiable `LiveData` object), increment the score, and decrement the score (ensuring it doesn’t go below 0).

The `ScoreActivity` sets up the UI and initializes the `ScoreViewModel`. It observes the `LiveData` score, so any changes to that score will automatically update the TextView displaying it. The buttons in the Activity invoke the increment and decrement methods on the `ViewModel`, altering the score.

The beauty of this architecture is the separation of concerns: the Activity manages UI and lifecycle events, while the ViewModel manages data and logic. The LiveData ensures that UI updates respect the lifecycle, avoiding issues like memory leaks or crashes due to updates on destroyed Activities.

4. Implement a Room Database Query

The Room persistence library provides an abstraction layer over SQLite, enabling more robust database access while harnessing the full power of SQLite. It simplifies many tasks but still requires a deep understanding of SQL when querying the database.

Task: Create a Room database that has a table named `Book` with fields `id`, `title`, and `author`. Implement a DAO (Data Access Object) method that fetches all books written by a specific author.

Input Format: The `Book` table will have a primary key `id` of type `int`, a `title` of type `String`, and an `author` of type `String`.

Constraints:

  • `id` is unique.
  • Both `title` and `author` fields have a maximum length of 100 characters.

Output Format: The DAO method should return a List of `Book` objects written by the specified author.

Sample Code:

“`java

@Entity(tableName = “book”)

public class Book {

    @PrimaryKey

    private int id;

    @ColumnInfo(name = “title”)

    private String title;

    @ColumnInfo(name = “author”)

    private String author;

    // Constructors, getters, setters…

}

@Dao

public interface BookDao {

    @Query(“SELECT * FROM book WHERE author = :authorName”)

    List<Book> getBooksByAuthor(String authorName);

}

@Database(entities = {Book.class}, version = 1)

public abstract class AppDatabase extends RoomDatabase {

    public abstract BookDao bookDao();

}

Explanation:

The `Book` class is annotated with `@Entity`, indicating that it’s a table in the Room database. The `id` field is marked as the primary key with `@PrimaryKey`. The other fields, `title` and `author`, are annotated with `@ColumnInfo` to specify their column names in the table.

The `BookDao` interface contains a method `getBooksByAuthor` which uses the `@Query` annotation to run an SQL query to fetch all books by a given author.

Finally, `AppDatabase` class is an abstract class that extends `RoomDatabase`, and it contains an abstract method to get an instance of the `BookDao`. This class is annotated with `@Database`, specifying the entities it comprises and the version of the database.

With this setup, any Android component can get an instance of `AppDatabase`, retrieve the `BookDao`, and use it to fetch books by a specific author from the underlying SQLite database.

5. Implement RecyclerView with DiffUtil

Using `RecyclerView` is a common task in Android development. It’s efficient, especially when displaying large lists or grids of data. To further enhance its efficiency, `DiffUtil` can be used to calculate differences between old and new lists, ensuring only actual changes get animated and rendered.

Task: Create a `RecyclerView` adapter that displays a list of strings. The adapter should use `DiffUtil` to efficiently handle updates to the list.

Input Format: The adapter will take in a list of strings.

Constraints: The list can contain up to 500 strings, with each string having a maximum length of 200 characters.

Output Format: A `RecyclerView` displaying the strings, efficiently updating its content whenever there’s a change in the input list.

Sample Code:

“`java

public class StringAdapter extends RecyclerView.Adapter<StringAdapter.ViewHolder> {

    private List<String> data;

    public StringAdapter(List<String> data) {

        this.data = data;

    }

    public void updateList(List<String> newData) {

        DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new StringDiffCallback(data, newData));

        this.data.clear();

        this.data.addAll(newData);

        diffResult.dispatchUpdatesTo(this);

    }

    @NonNull

    @Override

    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_string, parent, false);

        return new ViewHolder(view);

    }

    @Override

    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {

        holder.textView.setText(data.get(position));

    }

    @Override

    public int getItemCount() {

        return data.size();

    }

    static class ViewHolder extends RecyclerView.ViewHolder {

        TextView textView;

        public ViewHolder(@NonNull View itemView) {

            super(itemView);

            textView = itemView.findViewById(R.id.textView);

        }

    }

    static class StringDiffCallback extends DiffUtil.Callback {

        private final List<String> oldList;

        private final List<String> newList;

        public StringDiffCallback(List<String> oldList, List<String> newList) {

            this.oldList = oldList;

            this.newList = newList;

        }

        @Override

        public int getOldListSize() {

            return oldList.size();

        }

        @Override

        public int getNewListSize() {

            return newList.size();

        }

        @Override

        public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {

            return oldList.get(oldItemPosition).equals(newList.get(newItemPosition));

        }

        @Override

        public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {

            String oldString = oldList.get(oldItemPosition);

            String newString = newList.get(newItemPosition);

            return oldString.equals(newString);

        }

    }

}

Explanation:

The `StringAdapter` class extends the `RecyclerView.Adapter` and displays a list of strings. Its `updateList` method allows efficient updates using the `DiffUtil` utility. When new data is provided, `DiffUtil` calculates the difference between the old and new lists. The results, containing information about which items were added, removed, or changed, are then applied to the RecyclerView to ensure efficient updates.

The `StringDiffCallback` class, which extends `DiffUtil.Callback`, is responsible for determining the differences between two lists. The `areItemsTheSame` method checks if items (based on their position) in the old and new lists are the same, while the `areContentsTheSame` method checks if the content of items at specific positions in the old and new lists is the same.

Together, this setup ensures the `RecyclerView` updates efficiently, animating only actual changes, and avoiding unnecessary redraws.

6. Dependency Injection with Hilt

Dependency injection (DI) is a software design pattern that manages object creation and allows objects to be decoupled. In Android, Hilt is a DI library that is built on top of Dagger and simplifies its usage, making it more Android-friendly. 

Task: Use Hilt to inject a repository class into an Android ViewModel. Assume the repository provides a method `getUsers()`, which fetches a list of user names.

Input Format: A ViewModel class requiring a repository to fetch a list of user names.

Constraints:

  • Use Hilt for Dependency Injection.
  • The repository fetches a list of strings (user names).

Output Format: A ViewModel with an injected repository, capable of fetching and holding a list of user names.

Sample Code:

“`java

// Define a repository

public class UserRepository {

    public List<String> getUsers() {

        // Assume this method fetches user names, either from a local database, API, or other data sources.

        return Arrays.asList(“Alice”, “Bob”, “Charlie”);

    }

}

// Define a ViewModel

@HiltViewModel

public class UserViewModel extends ViewModel {

    private final UserRepository userRepository;

    @Inject

    public UserViewModel(UserRepository userRepository) {

        this.userRepository = userRepository;

    }

    public List<String> fetchUserNames() {

        return userRepository.getUsers();

    }

}

// Setting up Hilt Modules

@Module

@InstallIn(SingletonComponent.class)

public class RepositoryModule {

    @Provides

    @Singleton

    public UserRepository provideUserRepository() {

        return new UserRepository();

    }

}

Explanation:

In the given code, we start by defining a basic `UserRepository` class that simulates fetching a list of user names. 

Next, we define a `UserViewModel` class. The `@HiltViewModel` annotation tells Hilt to create an instance of this ViewModel and provides the required dependencies. The `@Inject` annotation on the constructor indicates to Hilt how to provide instances of the `UserViewModel`, in this case by injecting a `UserRepository` instance.

Lastly, a Hilt module (`RepositoryModule`) is defined using the `@Module` annotation. This module tells Hilt how to provide instances of certain types. In our example, the `provideUserRepository` method provides instances of `UserRepository`. The `@InstallIn(SingletonComponent.class)` annotation indicates that provided instances should be treated as singletons, ensuring that only one instance of `UserRepository` exists across the whole application lifecycle.

By following this setup, developers can effortlessly ensure dependencies (like the `UserRepository`) are provided to other parts of the application (like the `UserViewModel`) without manually creating and managing them.

7. Custom View with Measure and Draw

Custom views are a fundamental part of Android, allowing developers to create unique UI elements tailored to specific needs. Creating a custom view often requires understanding of the measure and draw process to ensure the view adjusts correctly to different screen sizes and resolutions.

Task: Create a simple custom view called `CircleView` that displays a colored circle. The view should have a customizable radius and color through XML attributes.

Input Format: Custom XML attributes for the `CircleView`: `circleColor` and `circleRadius`.

Constraints:

  • Implement the `onMeasure` method to ensure the view adjusts correctly.
  • Override the `onDraw` method to draw the circle.

Output Format: A custom view displaying a circle with specified color and radius.

Sample Code:

In `res/values/attrs.xml`:

“`xml

<declare-styleable name=”CircleView”>

    <attr name=”circleColor” format=”color” />

    <attr name=”circleRadius” format=”dimension” />

</declare-styleable>

In `CircleView.java`:

“`java

public class CircleView extends View {

    private int circleColor;

    private float circleRadius;

    private Paint paint;

    public CircleView(Context context, AttributeSet attrs) {

        super(context, attrs);

        paint = new Paint(Paint.ANTI_ALIAS_FLAG);

        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.CircleView);

        circleColor = ta.getColor(R.styleable.CircleView_circleColor, Color.RED);

        circleRadius = ta.getDimension(R.styleable.CircleView_circleRadius, 50f);

        ta.recycle();

        paint.setColor(circleColor);

    }

    @Override

    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        int desiredWidth = (int) (2 * circleRadius + getPaddingLeft() + getPaddingRight());

        int desiredHeight = (int) (2 * circleRadius + getPaddingTop() + getPaddingBottom());

        int widthMode = MeasureSpec.getMode(widthMeasureSpec);

        int widthSize = MeasureSpec.getSize(widthMeasureSpec);

        int heightMode = MeasureSpec.getMode(heightMeasureSpec);

        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        int width, height;

        if (widthMode == MeasureSpec.EXACTLY) {

            width = widthSize;

        } else if (widthMode == MeasureSpec.AT_MOST) {

            width = Math.min(desiredWidth, widthSize);

        } else {

            width = desiredWidth;

        }

        if (heightMode == MeasureSpec.EXACTLY) {

            height = heightSize;

        } else if (heightMode == MeasureSpec.AT_MOST) {

            height = Math.min(desiredHeight, heightSize);

        } else {

            height = desiredHeight;

        }

        setMeasuredDimension(width, height);

    }

    @Override

    protected void onDraw(Canvas canvas) {

        float cx = getWidth() / 2f;

        float cy = getHeight() / 2f;

        canvas.drawCircle(cx, cy, circleRadius, paint);

    }

}

Explanation:

The process of crafting a custom view in Android often involves a synergy between XML for configuration and Java/Kotlin for implementation. Let’s break down how the `CircleView` operates across these two realms:

XML Custom Attributes (`attrs.xml`):

  • Purpose: When creating a customizable view in Android, it’s imperative to define how it can be configured. Custom XML attributes allow the developer or designer to set specific properties directly in the layout XML files.
  • In Our Example: We defined two custom attributes in `attrs.xml`: `circleColor` and `circleRadius`. These dictate the color and size of the circle respectively when the view is used in an XML layout.

Java Implementation (`CircleView.java`):

    • Purpose: This is where the rubber meets the road. The Java (or Kotlin) code handles the logic, processing, and rendering of the custom view.
  • In Our Example: 
    • The constructor fetches the values of the custom attributes from the XML layout using `obtainStyledAttributes`. This means when you use the view in an XML layout and specify a color or radius, this is where it gets picked up and used.
    • The `onMeasure` method ensures the view adjusts its size according to the circle’s radius, also accounting for any padding.
    • The `onDraw` method takes care of the actual drawing of the circle, centered in the view, with the specified color and radius.

By mastering the interplay between XML attributes and Java/Kotlin logic, developers can craft custom UI elements that aren’t just visually appealing but also flexible and adaptive to various design specifications.

Resources to Improve AWS Knowledge

This article was written with the help of AI. Can you tell which parts?

The post 7 Android Interview Questions Every Developer Should Know appeared first on HackerRank Blog.

]]>
https://www.hackerrank.com/blog/android-interview-questions-every-developer-should-know/feed/ 0
5 AWS Interview Questions Every Developer Should Know https://www.hackerrank.com/blog/aws-interview-questions-every-developer-should-know/ https://www.hackerrank.com/blog/aws-interview-questions-every-developer-should-know/#respond Thu, 10 Aug 2023 12:45:44 +0000 https://www.hackerrank.com/blog/?p=19017 Cloud computing technology has firmly enveloped the world of tech, with Amazon Web Services (AWS)...

The post 5 AWS Interview Questions Every Developer Should Know appeared first on HackerRank Blog.

]]>
Abstract, futuristic image generated by AI

Cloud computing technology has firmly enveloped the world of tech, with Amazon Web Services (AWS) being one of the fundamental layers. Launched in 2006, AWS has evolved into a comprehensive suite of on-demand cloud computing platforms, tools, and services, powering millions of businesses globally.

The ubiquity of AWS is undeniable. As of Q1 2023, AWS commands 32% of the cloud market, underlining its pervasive influence. This widespread reliance on AWS reflects a continued demand for professionals adept in AWS services who can leverage its vast potential to architect scalable, resilient, and cost-efficient application infrastructures.

Companies are actively on the hunt for engineers, system architects, and DevOps engineers who can design, build, and manage AWS-based infrastructure, solve complex technical challenges, and take advantage of cutting-edge AWS technologies. Proficiency in AWS has become a highly desirable skill, vital for tech professionals looking to assert their cloud computing capabilities, and a critical criterion for recruiters looking to acquire top-tier talent.

In this article, we explore what an AWS interview typically looks like and introduce crucial AWS interview questions that every developer should be prepared to tackle. These questions are designed not only to test developers’ practical AWS skills but also to demonstrate their understanding of how AWS services interconnect to build scalable, reliable, and secure applications. Whether you’re a seasoned developer looking to assess and polish your AWS skills or a hiring manager seeking effective ways to evaluate candidates, this guide will prepare you to navigate AWS interviews with ease.

What is AWS?

Amazon Web Services, popularly known as AWS, is the reigning champ of cloud computing platforms. It’s an ever-growing collection of over 200 cloud services that include computing power, storage options, networking, and databases, to name a few. These services are sold on demand and customers pay for what they use, providing a cost-effective way to scale and grow.

AWS revolutionizes the way businesses develop and deploy applications by offering a scalable and durable platform that businesses of all sizes can leverage. Be it a promising startup or a Fortune 500 giant, many rely on AWS for a wide variety of workloads, including web and mobile applications, game development, data processing and warehousing, storage, archive, and many more.

What an AWS Interview Looks Like

Cracking an AWS interview involves more than just knowing the ins and outs of S3 buckets or EC2 instances. While a deep understanding of these services is vital, you also need to demonstrate how to use AWS resources effectively and efficiently in real-world scenarios.

An AWS interview typically tests your understanding of core AWS services, architectural best practices, security, and cost management. You could be quizzed on anything from designing scalable applications to deploying secure and robust environments on AWS. The level of complexity and depth of these questions will depend largely on the role and seniority level you are interviewing for.

AWS skills are not restricted to roles like cloud engineers or AWS solutions architects. Today, full-stack developers, DevOps engineers, data scientists, machine learning engineers, and even roles in management and sales are expected to have a certain level of familiarity with AWS. For instance, a full-stack developer might be expected to know how to deploy applications on EC2 instances or use Lambda for serverless computing, while a data scientist might need to understand how to leverage AWS’s vast suite of analytics tools.

That being said, irrespective of the role, some common themes generally crop up in an AWS interview. These include AWS’s core services like EC2, S3, VPC, Route 53, CloudFront, IAM, RDS, and DynamoDB; the ability to choose the right AWS services based on requirements; designing and deploying scalable, highly available, and fault-tolerant systems on AWS; data security and compliance; cost optimization strategies; and understanding of disaster recovery techniques.

1. Upload a File to S3

Amazon S3 (Simple Storage Service) is one of the most widely used services in AWS. It provides object storage through a web service interface and is used for backup and restore, data archiving, websites, applications, and many other tasks. In a work environment, a developer may need to upload files to S3 for storage or for further processing. Writing a script to automate this process can save a significant amount of time and effort, especially when dealing with large numbers of files. 

Task: Write a Python function that uploads a file to a specified S3 bucket.

Input Format: The input will be two strings: the first is the file path on the local machine, and the second is the S3 bucket name.

Output Format: The output will be a string representing the URL of the uploaded file in the S3 bucket.

Sample Code:

import boto3

def upload_file_to_s3(file_path, bucket_name):

    s3 = boto3.client('s3')

    file_name = file_path.split('/')[-1]

    s3.upload_file(file_path, bucket_name, file_name)

    file_url = f"https://{bucket_name}.s3.amazonaws.com/{file_name}"

    return file_url

Explanation:

This question tests a candidate’s ability to interact with AWS S3 using Boto3, the AWS SDK for Python. The function uses Boto3 to upload the file to the specified S3 bucket and then constructs and returns the file URL.

2. Launch an EC2 Instance

Amazon EC2 (Elastic Compute Cloud) is a fundamental part of many AWS applications. It provides resizable compute capacity in the cloud and can be used to launch as many or as few virtual servers as needed. Understanding how to programmatically launch and manage EC2 instances is a valuable skill for developers working on AWS, as it allows for more flexible and responsive resource allocation compared to manual management. 

Task: Write a Python function using Boto3 to launch a new EC2 instance.

Input Format: The input will be two strings: the first is the instance type, and the second is the Amazon Machine Image (AMI) ID.

Output Format: The output will be a string representing the ID of the launched EC2 instance.

Sample Code:

import boto3

def launch_ec2_instance(instance_type, image_id):

    ec2 = boto3.resource('ec2')

    instances = ec2.create_instances(

        ImageId=image_id,

        InstanceType=instance_type,

        MinCount=1,

        MaxCount=1

    )

    return instances[0].id

Explanation:

The function uses Boto3 to launch an EC2 instance with the specified instance type and AMI ID, and then returns the instance ID. This intermediate-level question tests a candidate’s knowledge of AWS EC2 operations. 

Explore verified tech roles & skills.

The definitive directory of tech roles, backed by machine learning and skills intelligence.

Explore all roles

3. Read a File from S3 with Node.js

Reading data from an S3 bucket is a common operation when working with AWS. This operation is particularly important in applications involving data processing or analytics, where data stored in S3 needs to be loaded and processed by compute resources. In this context, AWS Lambda is often used for running code in response to triggers such as changes in data within an S3 bucket. Therefore, a developer should be able to read and process data stored in S3. 

Task: Write a Node.js AWS Lambda function that reads an object from an S3 bucket and logs its content.

Input Format: The input will be an event object with details of the S3 bucket and the object key.

Output Format: The output will be the content of the file, logged to the console.

Sample Code:

const AWS = require('aws-sdk');

const s3 = new AWS.S3();

exports.handler = async (event) => {

    const params = {

        Bucket: event.Records[0].s3.bucket.name,

        Key: event.Records[0].s3.object.key

    };

    const data = await s3.getObject(params).promise();

    console.log(data.Body.toString());

};

Explanation:

This advanced-level question requires knowledge of AWS SDK for JavaScript (in Node.js) and Lambda. The above AWS Lambda function is triggered by an event from S3. The function then reads the content of the S3 object and logs it. 

4. Write to a DynamoDB Table

Amazon DynamoDB is a key-value and document database that delivers single-digit millisecond performance at any scale. It’s commonly used to support web, mobile, gaming, ad tech, IoT, and many other applications that need low-latency data access. Being able to interact with DynamoDB programmatically allows developers to build more complex, responsive applications and handle data in a more flexible way.

Task: Write a Python function using Boto3 to add a new item to a DynamoDB table.

Input Format: The input will be two strings: the first is the table name, and the second is a JSON string representing the item to be added.

Output Format: The output will be the response from the DynamoDB put operation.

Sample Code:

import boto3

import json

def add_item_to_dynamodb(table_name, item_json):

    dynamodb = boto3.resource('dynamodb')

    table = dynamodb.Table(table_name)

    item = json.loads(item_json)

    response = table.put_item(Item=item)

    return response

Explanation:

This function uses Boto3 to add a new item to a DynamoDB table. The function first loads the item JSON string into a Python dictionary, then adds it to the DynamoDB table. This question tests a candidate’s knowledge of how to interact with a DynamoDB database using Boto3.

5. Delete an S3 Object

Being able to delete an object from an S3 bucket programmatically is important for maintaining data hygiene and managing storage costs. For instance, you may need to delete objects that are no longer needed to free up space and reduce storage costs, or you might need to remove data for compliance reasons. Understanding how to perform this operation through code rather than manually can save a lot of time when managing large amounts of data.

Task: Write a Node.js function to delete an object from an S3 bucket.

Input Format: The input will be two strings: the first is the bucket name, and the second is the key of the object to be deleted.

Output Format: The output will be the response from the S3 delete operation.

Sample Code:

const AWS = require('aws-sdk');

const s3 = new AWS.S3();

async function delete_s3_object(bucket, key) {

    const params = {

        Bucket: bucket,

        Key: key

    };
    const response = await s3.deleteObject(params).promise();

    return response;
}

Explanation:

The function uses the AWS SDK for JavaScript (in Node.js) to delete an object from an S3 bucket and then returns the response. This expert-level question tests the candidate’s ability to perform S3 operations using the AWS SDK.

Resources to Improve AWS Knowledge

This article was written with the help of AI. Can you tell which parts?

The post 5 AWS Interview Questions Every Developer Should Know appeared first on HackerRank Blog.

]]>
https://www.hackerrank.com/blog/aws-interview-questions-every-developer-should-know/feed/ 0
7 CSS Interview Questions Every Developer Should Know https://www.hackerrank.com/blog/css-interview-questions-every-developer-should-know/ https://www.hackerrank.com/blog/css-interview-questions-every-developer-should-know/#respond Thu, 03 Aug 2023 12:45:14 +0000 https://www.hackerrank.com/blog/?p=19008 Despite the ever-evolving nature of web development, some technologies have firmly established themselves as long-standing...

The post 7 CSS Interview Questions Every Developer Should Know appeared first on HackerRank Blog.

]]>
Abstract, futuristic image generated by AI

Despite the ever-evolving nature of web development, some technologies have firmly established themselves as long-standing pillars. CSS — or Cascading Style Sheets —  is one such technology that, since its inception in the late ’90s, continues to play a fundamental role in how we design websites today. CSS is the magic wand that transforms the fundamental structure of a webpage, built by HTML, into a visually compelling and user-friendly interface.

The technology’s widespread use – 97.1% of all websites use CSS underscores its pervasive influence in shaping the internet’s look and feel. This ubiquity of CSS means there’s a constant demand for skilled CSS professionals who can leverage its potential to create engaging, responsive, and interactive web experiences.

However, with high demand comes high expectations. Employers are actively seeking developers who can use CSS to solve complex design problems, implement seamless user experiences, and efficiently manage styles across various device screens. Mastery over CSS, therefore, is a highly sought-after skill, essential for developers seeking to showcase their front-end prowess. And it’s a key consideration for recruiters aiming to bring in top-notch talent.

This post aims to guide you through a series of carefully selected and progressively more challenging CSS interview questions. We’ll provide comprehensive explanations and illustrative code snippets. Whether you’re a developer wanting to brush up your CSS skills or a hiring manager looking for the right questions to assess your candidates, this guide is designed to help you approach your next CSS interview with confidence.

Understanding CSS

When you land on a beautifully designed web page with dynamic visuals, attractive color schemes, and easy-to-navigate layouts, you’re witnessing the result of well-implemented CSS. CSS is a cornerstone of web development, and its main purpose is to describe how HTML elements should be displayed on the screen. 

CSS, along with HTML and JavaScript, forms the trinity of front-end web development. While HTML provides the structural skeleton of a webpage and JavaScript adds functionality, CSS is responsible for the aesthetics. It controls the layout of multiple web pages simultaneously, adjusts elements to different screen sizes, and applies consistent styling across a website. 

This language is stylesheet-based, which means you write rules that tell browsers how to render the HTML elements on a page. For example, you might use CSS to specify that all the heading elements on a website should be bold and blue, or that a specific paragraph should be indented and have a larger font size. 

CSS is not just about making websites look good; it also enhances the user experience. With it, developers can create responsive designs that adapt to different devices, improve load times by optimizing styles, and increase accessibility for users with special needs. 

But why does this all matter in an interview context? When technical teams are recruiting for roles that involve any aspect of front-end development, CSS knowledge is almost invariably a requirement. This is because understanding CSS is key to being able to create web applications that not only function well but also provide an excellent user experience. So, whether you’re a software engineer, a web developer, a UI/UX designer, or in any role that touches on the user interface, CSS should be in your wheelhouse.

The CSS Interview: What to Expect

A CSS interview is an opportunity for candidates to showcase their skills in transforming plain, static HTML into dynamic, visually appealing web interfaces. At the same time, it allows recruiters to assess whether a candidate can effectively use CSS to meet design specifications, troubleshoot layout issues, and enhance the user experience.

Interviews focusing on CSS will typically go beyond basic syntax and selectors, delving into advanced topics such as layout techniques (like CSS Grid and Flexbox), CSS preprocessors, animations, responsive design, performance optimization, and handling browser compatibility issues.

The types of questions asked can vary widely depending on the role and the company. For instance, a front-end developer position might include more in-depth questions about CSS animations and transitions, while a full-stack developer role could cover how CSS fits into the broader context of a project, including interactions with JavaScript and back-end technologies.

The roles that often require CSS skills are vast and varied. Besides the obvious front-end web developer and full-stack developer, other roles like UI/UX designers, software engineers, and even roles in marketing or SEO could require a firm understanding of CSS. In some interviews, you might be asked to write CSS code in real time or refactor an existing piece of CSS code. In others, you may need to review a snippet of CSS and HTML code and discuss how it could be improved for better efficiency and maintainability.

1. Implementing a Class for CSS Colors

This question examines a developer’s understanding of CSS colors, which play a crucial role in styling web pages, and their ability to model concepts using object-oriented programming.

Task: Write a JavaScript class called `CSSColor` that represents a color in CSS. This class should have a constructor that takes three arguments: red, green, and blue. It should also have a method called `toCSS()` that returns the color in CSS format.

Input Format: The constructor will take three integers, each representing the red, green, and blue components of the color. The `toCSS()` method will take no arguments.

Constraints:

  • The values for red, green, and blue will be integers.
  • Each value will be between 0 and 255, inclusive.

Output Format: The `toCSS()` method will return a string representing the color in CSS format.

Sample Input:

let color = new CSSColor(255, 0, 0);

Sample Output:

console.log(color.toCSS()); // "rgb(255, 0, 0)"

Sample Code:

class CSSColor {

    constructor(red, green, blue) {

        this.red = red;

        this.green = green;

        this.blue = blue;

    }

    

    toCSS() {

        return `rgb(${this.red}, ${this.green}, ${this.blue})`;

    }

}

Explanation

The `CSSColor` class has a constructor that sets the red, green, and blue properties of the class based on the arguments passed in. The `toCSS()` method then returns a string that formats these properties in the CSS rgb format.

This question challenges developers to demonstrate their understanding of CSS colors and their capacity to use object-oriented programming to represent real-world concepts. This kind of problem-solving ability is invaluable in a professional setting, where developers must often create custom abstractions to solve unique challenges.

2. Implementing a Function to Apply CSS Styles

This question delves deeper into a developer’s knowledge of how CSS styles are applied to HTML elements through JavaScript. This checks their capability to manipulate the Document Object Model (DOM), an essential skill for building interactive web applications.

Task: Write a JavaScript function called `applyStyles` that takes a CSS selector and a style object as inputs and applies the styles to all elements that match the selector.

Input Format: The function will take two arguments: a string representing a CSS selector and an object where the keys are CSS properties and the values are the desired styles.

Constraints:

  • The CSS selector will be a valid string selector.
  • The style object will contain at least one property-value pair.

Sample Input:

applyStyles('p', { color: 'red', fontWeight: 'bold' });

Sample Code:

function applyStyles(selector, styles) {

    let elements = document.querySelectorAll(selector);

    for (let i = 0; i < elements.length; i++) {

        for (let style in styles) {

            elements[i].style[style] = styles[style];

        }

    }

}

Explanation:

The `applyStyles` function uses the `querySelectorAll` method to get all the elements that match the provided selector. It then iterates over these elements. For each element, it loops through each property in the styles object and assigns the corresponding value to that property on the element’s `style` object.

This question ups the difficulty from the previous one by not only requiring the candidate to work with CSS but also to manipulate HTML elements using JavaScript. It provides a good gauge of the candidate’s proficiency with JavaScript and their understanding of how CSS and JavaScript can interact in a web development context.

3. Implementing a Function to Rotate an Element

This question tests a developer’s expertise in transforming HTML elements using CSS, a powerful feature that allows developers to animate elements and create engaging user interfaces. 

Task: Write a JavaScript function called `rotateElement` that takes an HTML element’s id and a rotation angle as inputs and rotates the element to the specified angle.

Input Format: The function will take two arguments: a string representing the id of an HTML element and a number representing the rotation angle in degrees.

Constraints:

  • The id will correspond to an existing HTML element.
  • The rotation angle will be a valid number.

Sample Input:

rotateElement('myDiv', 45);

Sample Code:

function rotateElement(id, angle) {

    let element = document.getElementById(id);

    element.style.transform = `rotate(${angle}deg)`;

}

Explanation:

The `rotateElement` function uses the `getElementById` method to find the HTML element with the specified id. It then applies a rotation transformation to this element by setting its `transform` style to `rotate(${angle}deg)`, where `${angle}` is replaced with the provided angle.

This question requires an understanding of CSS transformations, which are a complex but powerful feature of CSS. Knowing how to use these transformations is crucial for creating modern, dynamic web pages. It also continues to test the candidate’s proficiency with JavaScript, particularly their ability to manipulate HTML elements and CSS styles.

Explore verified tech roles & skills.

The definitive directory of tech roles, backed by machine learning and skills intelligence.

Explore all roles

4. Implementing a Function to Create a Grid Layout

This question delves into the developer’s knowledge of CSS grid layout, an advanced and powerful tool for creating responsive web layouts. It also tests their ability to generate HTML elements dynamically with JavaScript.

Task: Write a JavaScript function called `createGrid` that takes two arguments: the number of rows and the number of columns. The function should create a grid of `div` elements with the specified number of rows and columns and apply CSS grid layout to arrange these divs into a grid.

Constraints: Both the number of rows and columns will be positive integers.

Sample Input:

let grid = createGrid(3, 3);

Sample Code:

function createGrid(rows, columns) {

    let grid = document.createElement('div');

    grid.style.display = 'grid';

    grid.style.gridTemplateRows = `repeat(${rows}, 1fr)`;

    grid.style.gridTemplateColumns = `repeat(${columns}, 1fr)`;

    

    for (let i = 0; i < rows * columns; i++) {

        let cell = document.createElement('div');

        cell.textContent = `Cell ${i + 1}`;

        grid.appendChild(cell);

    }

    

    return grid;

}

Explanation:

The `createGrid` function begins by creating a new div element and setting its display style to ‘grid’. It then uses the CSS `gridTemplateRows` and `gridTemplateColumns` properties to define the grid’s structure, using the `repeat` function to create the specified number of rows and columns.

The function then enters a loop that runs once for each cell in the grid. In each iteration, it creates a new div, sets its text content to indicate its position, and appends it to the grid.

Finally, the function returns the grid element, which now has the desired grid structure and contains the appropriate number of cells.

This question raises the difficulty by requiring candidates to generate HTML elements dynamically and style them with an advanced CSS feature: the grid layout. This represents a practical task that developers might often face when creating complex, responsive web layouts.

5. Implementing a Function for Responsive Design

In this question, we’re testing the developer’s knowledge of CSS media queries, an important tool for creating responsive designs that adapt to different screen sizes. 

Task: Write a JavaScript function named `createResponsiveDiv` that creates a `div` element. This `div` should be styled such that it is 100% of the browser window’s width when the window is less than 600px wide and 50% of the browser window’s width otherwise.

Input Format: The function takes no arguments.

Constraints: The browser window’s width will be a positive number.

Output Format: The function will return an HTML `div` element that is styled according to the responsive design requirements.

Sample Input:

let responsiveDiv = createResponsiveDiv();

Sample Code:

function createResponsiveDiv() {

    let div = document.createElement('div');

    let style = document.createElement('style');

    style.innerHTML = `

        #responsiveDiv {

            width: 100%;

        }

        @media (min-width: 600px) {

            #responsiveDiv {

                width: 50%;

            }

        }

    `;

    document.head.appendChild(style);

    div.id = "responsiveDiv";

    return div;

}

Explanation:

The `createResponsiveDiv` function starts by creating a new `div` element. 

Next, it creates a `style` element and sets its innerHTML to the desired CSS. This CSS first sets the width of the `div` (which will be given the id “responsiveDiv”) to 100 percent. Then, it uses a media query to change this width to 50 percent if the width of the viewport is at least 600px. The style element is then appended to the `head` of the document.

Finally, the function gives the `div` the id “responsiveDiv” and returns it.

This question is the most challenging yet, requiring a strong understanding of media queries and how they can be used to create responsive designs. It also continues to test the developer’s skills in using JavaScript to create and manipulate HTML and CSS.

6. Implementing a Function to Apply a CSS Animation

This question evaluates a developer’s understanding of CSS animations, a sophisticated feature of CSS that’s fundamental to creating interactive and engaging web experiences. 

Task: Write a JavaScript function named `applyAnimation` that takes an HTML element’s id and applies a CSS keyframe animation to it. The animation should gradually change the element’s background color from red to blue over a period of 5 seconds.

Input Format: The function will take one argument: a string representing the id of an HTML element.

Constraints: The id will correspond to an existing HTML element.

Sample Input:

applyAnimation('myDiv');

Sample Code:

function applyAnimation(id) {

    let element = document.getElementById(id);

    let style = document.createElement('style');

    style.innerHTML = `

        @keyframes colorChange {

            0% {background-color: red;}

            100% {background-color: blue;}

        }

        #${id} {

            animation: colorChange 5s;

        }

    `;

    document.head.appendChild(style);

}

Explanation:

The `applyAnimation` function starts by getting a reference to the HTML element with the specified id using the `getElementById` method.

Next, it creates a `style` element and sets its innerHTML to define a CSS keyframe animation named `colorChange`. This animation gradually changes an element’s background color from red to blue. The CSS also applies this animation to the element with the specified id and sets the animation’s duration to 5 seconds. The style element is then appended to the `head` of the document.

This question significantly raises the difficulty level by requiring the candidate to use CSS keyframes, a complex but powerful feature that is crucial for creating animations in CSS. 

7. Creating a CSS Variable Manipulation Function

The final question explores the developer’s knowledge of CSS Variables (or custom properties), a more advanced feature of CSS. Custom properties provide a powerful way to create reusable values in CSS, which can be manipulated via JavaScript.

Task: Write a JavaScript function named `changeTheme` that takes two parameters: an HTML element’s id and a string representing a color. The function should change the value of the CSS variable `–theme-color` for the specified element to the provided color.

Input Format: The function will take two arguments: a string representing the id of an HTML element and another string representing a color.

Constraints:

  • The id will correspond to an existing HTML element.
  • The color will be a valid CSS color.

Sample Input:

changeTheme('myDiv', 'purple');

Sample Code:

function changeTheme(id, color) {

    let element = document.getElementById(id);

    element.style.setProperty('--theme-color', color);

}

Explanation:

The `changeTheme` function begins by getting a reference to the HTML element with the specified id.

Then, it uses the `setProperty` method to change the value of the CSS variable `–theme-color` for that element to the provided color.

This question represents a culmination of the candidate’s CSS and JavaScript knowledge, requiring them to understand how to manipulate CSS variables — a feature that brings a lot of power and flexibility to CSS. CSS variables can help reduce repetition, provide better scalability, and even allow for things like theme switching in CSS.

Resources to Improve HTML Knowledge

 

This article was written with the help of AI. Can you tell which parts?

The post 7 CSS Interview Questions Every Developer Should Know appeared first on HackerRank Blog.

]]>
https://www.hackerrank.com/blog/css-interview-questions-every-developer-should-know/feed/ 0
8 HTML Interview Questions Every Developer Should Know https://www.hackerrank.com/blog/html-interview-questions-developers-should-know/ https://www.hackerrank.com/blog/html-interview-questions-developers-should-know/#respond Tue, 01 Aug 2023 12:45:12 +0000 https://www.hackerrank.com/blog/?p=18999 HTML is an enduring pillar in the world of web development, continually proving its worth...

The post 8 HTML Interview Questions Every Developer Should Know appeared first on HackerRank Blog.

]]>
Abstract, futuristic image generated by AI

HTML is an enduring pillar in the world of web development, continually proving its worth even as technologies advance. Its power, ubiquity, and simplicity make it an essential skill for any aspiring web developer. As the backbone of virtually all websites, a solid understanding of HTML can unlock numerous opportunities and serve as a valuable asset in the tech industry.

HTML is more than just a static markup language; it provides a structure that brings content to life on the web. Its proficiency provides developers with the ability to craft and control the visual and structural aspects of a webpage, resulting in an enriched user experience. Alongside CSS and JavaScript, HTML forms the triad that orchestrates every interaction between a user and a website.

For those preparing to ace an HTML interview, it’s imperative to extend beyond the basic tags and attributes. The real challenge lies in demonstrating the ability to leverage HTML in creating clean, accessible, and responsive web layouts, which is likely to be the focus of an interview scenario. 

In this post, we delve deeper into the importance of HTML, demystify what a typical HTML interview entails, and provide a sequence of progressively challenging HTML interview questions. These questions are designed to polish your HTML skills and prepare you for the kinds of problems you are likely to face in an interview setting. Ready to elevate your HTML game? Let’s dive in.

Understanding HTML

HTML, or HyperText Markup Language, stands as the bread and butter of web development and is the markup language used to structure and present content on the web. Despite not being a programming language, its impact is vast and fundamental to how we interact with the digital world. From the web pages we visit to the online forms we fill out to the buttons we click — behind the scenes, HTML is working its magic.

Unlike programming languages that have functions, loops, and logic, HTML uses a set of pre-defined tags to define the structure and semantic meaning of the web content. Everything from headings represented by `<h1>` to `<h6>` tags to paragraphs encapsulated within the `<p>` tags and links denoted by `<a>` tags come together to create the structure of a web page.

Example:

<h1>This is a heading</h1>

<p>This is a paragraph.</p>

<a href="http://www.example.com">This is a link</a>

However, HTML isn’t just about defining the structure. It’s about enhancing the accessibility and optimizing web content for search engines. The tags and attributes in HTML play a crucial role in making web content accessible to all users, including those using assistive technologies, and they help search engines understand the content and relevance of your web pages, improving your website’s SEO.

So, if you want to insert an image into a webpage, the `<img>` tag with the `src` attribute is used. This not only displays the image but also informs the browser and search engines about the presence of an image.

<img src="image.jpg" alt="A description of the image">

With this context, it’s clear that a robust understanding of HTML is vital for anyone looking to succeed in the field of web development, and it’s equally essential for those looking to hire the best talent. An HTML interview is where these expectations meet reality, where you demonstrate your ability to leverage HTML to create well-structured, accessible, and SEO-friendly websites. 

What Does an HTML Interview Look Like?

Stepping into an HTML interview can be an engaging, challenging experience, but can also be one full of opportunities to showcase your skills and knowledge. While HTML is often considered a basic skill for web developers, interviews centered around it can be far from simple.

An HTML interview is an opportunity to showcase how well you understand and can apply this essential web language. The questions can range from fundamental concepts like “What is the `DOCTYPE`?”, to more complex ones involving the creation of specific layouts or solving accessibility issues.

Coding tasks could involve creating semantic HTML structures, building responsive tables, or dealing with forms and validations. You may also be asked to explain how certain HTML elements affect SEO or web accessibility. You’re not just showcasing your knowledge of HTML tags and attributes, but demonstrating an understanding of when and why to use them, and how they interact with CSS, JavaScript, and browsers.

HTML interviews are not exclusive to front-end developer roles. Full-stack developers, software engineers, UX/UI designers, and even content strategists might find themselves facing HTML interview questions. Any position that involves the creation or manipulation of web content can potentially require a sound understanding of HTML. These roles often expect you to build or design web pages, fix UI bugs, or collaborate closely with developers, making HTML an essential skill.

Now that we’ve outlined what an HTML interview might look like and the roles that could require HTML skills, let’s move on to some interview questions. These questions range from intermediate to advanced, and each one gets progressively more challenging. Whether you’re a developer preparing for an interview or a recruiter seeking question inspiration, the following problems will serve as a beneficial resource. 

1. Semantic HTML

Semantic HTML is an essential concept in modern web development, focusing on using the correct tags to provide meaning to the content and improve accessibility and SEO. Understanding this concept is key for any developer who wants to write clean, accessible, and SEO-friendly code.

Task: The task here is to rewrite a simple HTML code snippet using semantic HTML tags. 

Input: An HTML snippet using non-semantic `div` tags.

<div id="header">This is the Header</div>

<div id="nav">This is the Navigation</div>

<div id="main">This is the Main Content</div>

<div id="footer">This is the Footer</div>

Constraints:

  • Replace the `div` tags with appropriate semantic HTML tags.
  • Do not change the content inside the tags.
  • Do not add additional attributes to the tags.

Sample Answer

<header>This is the Header</header>

<nav>This is the Navigation</nav>

<main>This is the Main Content</main>

<footer>This is the Footer</footer>

Explanation

This task revolves around the use of semantic HTML. The goal is to replace the generic `div` tags with corresponding semantic tags that provide more information about the type of content they contain.

  • `<header>` is a semantic HTML tag that is typically used to contain introductory content or navigation links. In this case, it replaces the `div` with the id of “header”.
  • `<nav>` is used for sections of a page that contain navigation links. It replaces the `div` with the id of “nav”.
  • `<main>` is used for the dominant content of the body of a document or application. It replaces the `div` with the id of “main”.
  • `<footer>` is used for containing information about the author, copyright information, etc. It replaces the `div` with the id of “footer”.

Using semantic HTML tags in this way improves the accessibility of the webpage and helps search engines understand the content better.

2. Form Validation

Form validation is a critical aspect of web development. It enhances UX and security by ensuring that users provide the required information in the correct format before submitting a form. HTML5 introduced several form validation attributes that simplify this task.

Task: Create an HTML form that includes validation. The form should have the following fields:

  • A “Name” field that is required and should accept only alphabetic characters.
  • An “Email” field that is required and should accept a valid email address.
  • A “Password” field that is required and should be at least 8 characters long.
  • A “Submit” button to submit the form.

Constraints:

  • Use HTML5 validation attributes.
  • Do not use JavaScript or any external libraries for validation.
  • Do not include any CSS. The focus is purely on HTML structure and validation.

Sample Answer

<form>

    <label for="name">Name:</label><br>

    <input type="text" id="name" name="name" pattern="[A-Za-z]+" required><br>

    <label for="email">Email:</label><br>

    <input type="email" id="email" name="email" required><br>

    <label for="password">Password:</label><br>

    <input type="password" id="password" name="password" minlength="8" required><br>

    <input type="submit" value="Submit">

</form>

Explanation

The task tests the understanding of HTML forms and the use of HTML5 validation attributes:

  • The `required` attribute is used to specify that an input field must be filled out before submitting the form.
  • The `pattern` attribute in the “Name” field uses a regular expression `[A-Za-z]+` to accept only alphabetic characters.
  • The `type` attribute with the value `email` in the “Email” field enforces valid email input.
  • The `minlength` attribute in the “Password” field enforces that the password should be at least 8 characters long.

The correct usage of these HTML5 validation attributes can significantly improve the user experience by providing instant feedback before the form is submitted, reducing the load on the server.

3. Accessible Tables

Accessibility is a critical aspect of web development. HTML provides tools for making your web content accessible to people with disabilities, and understanding how to use these tools is essential.

Task: Your task is to create an accessible HTML table for a class schedule. The table should have three columns: “Day,” “Subject,” and “Time.” It should have data for five days from Monday to Friday.

Constraints:

  • Use appropriate tags to make the table headers readable by screen readers.
  • Do not include any CSS. The focus is purely on HTML structure and accessibility.

Sample Answer

<table>

    <thead>

        <tr>

            <th scope="col">Day</th>

            <th scope="col">Subject</th>

            <th scope="col">Time</th>

        </tr>

    </thead>

    <tbody>

        <tr>

            <td>Monday</td>

            <td>Math</td>

            <td>9:00-10:00</td>

        </tr>

        <tr>

            <td>Tuesday</td>

            <td>English</td>

            <td>10:00-11:00</td>

        </tr>

        <tr>

            <td>Wednesday</td>

            <td>Physics</td>

            <td>11:00-12:00</td>

        </tr>

        <tr>

            <td>Thursday</td>

            <td>Biology</td>

            <td>12:00-1:00</td>

        </tr>

        <tr>

            <td>Friday</td>

            <td>History</td>

            <td>1:00-2:00</td>

        </tr>

    </tbody>

</table>

Explanation

The task is about creating an accessible table in HTML. The `table` element is used to create a table, while the `thead` and `tbody` elements are used to group the content in the table header and the body respectively. This can provide benefits for screen reader users.

Each row of the table is created using the `tr` element, and within these rows, the `th` element is used for table headers, and the `td` element is used for table data cells.

Importantly, the `scope` attribute is used in the `th` elements. The `scope=”col”` attribute makes it clear that these headers are for columns. This helps screen readers understand the structure of the table, making your table more accessible.

Explore verified tech roles & skills.

The definitive directory of tech roles, backed by machine learning and skills intelligence.

Explore all roles

4. Embedding Content

One of the powerful features of HTML is the ability to embed various types of content, such as images, videos, and audio files. Understanding how to use these elements is crucial for creating rich, interactive web pages.

Task: Your task is to write HTML code to accomplish the following:

  • Embed a YouTube video with the id “zxcvbnm.” It should autoplay when the page loads, but the sound should be muted.
  • Below the video, place an image with the source URL “https://example.com/image.jpg” and an alt text “Example Image.”
  • Finally, add a download link for a PDF file at “https://example.com/document.pdf” with the link text “Download PDF.”

Constraints:

  • Use the appropriate HTML tags for each type of content.
  • Do not include any CSS or JavaScript. The focus is purely on HTML structure.

Sample Answer

<iframe width="560" height="315" src="https://www.youtube.com/embed/zxcvbnm?autoplay=1&mute=1" frameborder="0" allow="autoplay"></iframe>

<img src="https://example.com/image.jpg" alt="Example Image">

<a href="https://example.com/document.pdf" download="document">Download PDF</a>

Explanation

This task assesses your ability to embed different types of content using HTML.

  • YouTube videos can be embedded using the `iframe` tag. The `src` attribute is set to the URL of the video, which includes parameters for autoplaying (`autoplay=1`) and muting (`mute=1`).
  • Images can be included using the `img` tag, where the `src` attribute specifies the image URL and the `alt` attribute provides alternative text for screen readers or in case the image can’t be loaded.
  • A link for downloading a file can be created using the `a` tag. The `href` attribute specifies the file URL, and the `download` attribute is used to trigger the download action when the link is clicked. The link text is placed between the opening and closing `a` tags.

5. Understanding the DOM

The Document Object Model (DOM) is a crucial concept in web development. It provides a structured representation of the document and defines a way that the structure can be manipulated. A deep understanding of the DOM is essential for interactive web development.

Task

Consider the following HTML code:

<div id="parent">

    <div id="child1" class="child">Child 1</div>

    <div id="child2" class="child">Child 2</div>

    <div id="child3" class="child">Child 3</div>

</div>

How would you select and manipulate the DOM elements in the following situations?

  1. Select the div with id “parent”.
  2. Select all divs with the class “child”.
  3. Change the text content of the div with id “child2” to “Second Child”.

Constraints:

  • Provide the JavaScript code that would accomplish each task.
  • You can use either plain JavaScript or jQuery.
  • Do not modify the original HTML code.

Sample Answer

Using plain JavaScript:

// 1. Select the div with id "parent".

var parentDiv = document.getElementById("parent");

// 2. Select all divs with the class "child".

var childDivs = document.getElementsByClassName("child");

// 3. Change the text content of the div with id "child2" to "Second Child".

document.getElementById("child2").textContent = "Second Child";

Or, using jQuery:

// 1. Select the div with id "parent".

var parentDiv = $("#parent");

// 2. Select all divs with the class "child".

var childDivs = $(".child");

// 3. Change the text content of the div with id "child2" to "Second Child".

$("#child2").text("Second Child");

Explanation

This task is about understanding the DOM and how to manipulate it using JavaScript or jQuery:

  • In JavaScript, `document.getElementById` is used to select an element by its id, and `document.getElementsByClassName` is used to select all elements with a specific class. To change the text content of an element, we can use the `textContent` property.
  • In jQuery, we can use `$(“#id”)` to select an element by id and `$(“.class”)` to select elements by class. The `.text()` method is used to change the text content of an element.

6. Advanced Form Validation

HTML forms with complex validation rules can ensure that user input is not only present but also meets a specific format or set of conditions. The `pattern` attribute in HTML5 allows developers to define such rules using regular expressions.

Task: Modify the sign-up form from Question #2 to include the following changes to the password field: Password (required, at least 8 characters, must include at least one digit and one special character)

Constraints:

  • Use the `pattern` attribute to define the new validation rules for the password.
  • The form should not be submitted unless the password meets all the specified requirements.
  • Do not include any CSS or JavaScript. The focus is purely on HTML structure and attributes.

Sample Answer

<form>

    <label for="name">Full Name:</label><br>

    <input type="text" id="name" name="name" required minlength="5"><br>  

    <label for="email">Email Address:</label><br>

    <input type="email" id="email" name="email" required><br>   

    <label for="password">Password:</label><br>

    <input type="password" id="password" name="password" required pattern="(?=.*\d)(?=.*[!@#$%^&*]).{8,}"><br>    

    <label for="bio">Bio:</label><br>

    <textarea id="bio" name="bio" maxlength="500"></textarea><br>    

    <input type="submit" value="Sign Up">

</form>

Explanation

In addition to the form creation and validation concepts explained in the previous question, this task introduces the `pattern` attribute:

  • The `pattern` attribute is used to define a regular expression — the input field’s value is checked against this expression when the form is submitted. If the value does not match the pattern, the form cannot be submitted.
  • The regular expression `(?=.*\d)(?=.*[!@#$%^&*]).{8,}` is used to enforce the new password rules: it ensures that the password has at least one digit (`(?=.*\d)`), includes at least one special character (`(?=.*[!@#$%^&*])`), and is at least 8 characters long (`.{8,}`).

This question tests the candidate’s understanding of complex form validation using HTML5’s `pattern` attribute and regular expressions, crucial for creating secure and user-friendly forms. For real-world applications, it’s important to note that client-side validation is not enough for security; server-side validation is also necessary.

7. Accessibility and ARIA

Web accessibility ensures that websites, tools, and technologies are designed and developed so that people with disabilities can use them. ARIA (Accessible Rich Internet Applications) is a set of attributes that help increase the accessibility of web pages, particularly dynamic content and user interface components developed with JavaScript.

Task: You are provided with the following HTML code for a custom dropdown menu:

<div id="dropdown" onclick="toggleDropdown()">

    <button>Menu</button>

    <div id="dropdown-content">

        <a href="#">Option 1</a>

        <a href="#">Option 2</a>

        <a href="#">Option 3</a>

    </div>

</div>

The dropdown content (`#dropdown-content`) is hidden by default and shown when the user clicks on the “Menu” button.

Make the necessary modifications to this HTML code to make the dropdown menu accessible using ARIA attributes.

Constraints:

  • Use appropriate ARIA roles, properties, and states.
  • Assume the function `toggleDropdown()` changes the visibility of `#dropdown-content` and the text of the button to either “Menu” (when the dropdown is closed) or “Close” (when the dropdown is open).

Sample Answer

<div id="dropdown" onclick="toggleDropdown()" role="menubar">

    <button id="dropdown-button" aria-haspopup="true" aria-controls="dropdown-content">Menu</button>

    <div id="dropdown-content" role="menu" aria-labelledby="dropdown-button">

        <a href="#" role="menuitem">Option 1</a>

        <a href="#" role="menuitem">Option 2</a>

        <a href="#" role="menuitem">Option 3</a>

    </div>

</div>

Explanation

ARIA attributes are used to improve the accessibility of the dropdown menu:

  • The `role` attribute is used to describe what the purpose of a certain HTML element is. Here, we’ve used the roles `menubar`, `menu`, and `menuitem` to provide the dropdown and its items with semantics that assistive technologies can understand.
  • `aria-haspopup=”true”` indicates that the button has a popup menu.
  • `aria-controls=”dropdown-content”` indicates that the dropdown button controls the visibility of the `#dropdown-content`.
  • `aria-labelledby=”dropdown-button”` establishes a relationship between the dropdown content and the button that controls it.

Remember, this is only part of making a dropdown menu accessible. Proper keyboard interactions would also need to be implemented with JavaScript for full accessibility. ARIA doesn’t change behavior, but it helps assistive technologies understand the purpose, state, and functionality of custom controls. 

If this question seems too difficult, we can select a less complex HTML interview question. Otherwise, it’s an excellent way to test candidates’ understanding of web accessibility, a crucial aspect of modern web development.

8. Working with HTML5 Canvas

The HTML5 `<canvas>` element is used to draw graphics on a web page. The drawing on a `<canvas>` must be done with JavaScript, making it a powerful tool to create graphics, animations, and even game assets.

Task: Using HTML5’s Canvas API, create a 500px by 500px `<canvas>` element that draws a red rectangle that is 200px wide and 100px tall at the center of the canvas.

Constraints:

  • The dimensions of the `<canvas>` must be set to 500px by 500px using HTML attributes.
  • The rectangle should be exactly centered both vertically and horizontally in the `<canvas>`.

Sample Answer

<canvas id="canvas" width="500" height="500"></canvas>

<script>

    var canvas = document.getElementById('canvas');

    var ctx = canvas.getContext('2d');

    var rectWidth = 200;

    var rectHeight = 100;

    ctx.fillStyle = 'red';

    ctx.fillRect((canvas.width - rectWidth) / 2, (canvas.height - rectHeight) / 2, rectWidth, rectHeight);

</script>

Explanation

  • First, we create a `<canvas>` element with the specified width and height using HTML attributes. 
  • Next, we use JavaScript to get a reference to the `<canvas>` and its drawing context, which we’ll need to draw on the `<canvas>`.
  • The width and height of the rectangle are set to the specified values. 
  • The `fillStyle` property of the context is set to `’red’`, which will be the color of the rectangle.
  • Finally, the `fillRect()` method is used to draw the rectangle. This method takes four parameters: the x and y coordinates of the upper-left corner of the rectangle, and the width and height of the rectangle. To center the rectangle, we calculate the x and y coordinates as `(canvas.width – rectWidth) / 2` and `(canvas.height – rectHeight) / 2`, respectively.

This question tests a candidate’s familiarity with the HTML5 Canvas API, which is a powerful tool for generating dynamic graphics and animations in web applications.

Resources to Improve HTML Knowledge

This article was written with the help of AI. Can you tell which parts?

The post 8 HTML Interview Questions Every Developer Should Know appeared first on HackerRank Blog.

]]>
https://www.hackerrank.com/blog/html-interview-questions-developers-should-know/feed/ 0
7 C Interview Questions Every Developer Should Know https://www.hackerrank.com/blog/7-c-interview-questions-every-developer-should-know/ https://www.hackerrank.com/blog/7-c-interview-questions-every-developer-should-know/#respond Mon, 17 Jul 2023 12:45:52 +0000 https://www.hackerrank.com/blog/?p=18917 The programming language C stands as a key pillar in the world of computer science,...

The post 7 C Interview Questions Every Developer Should Know appeared first on HackerRank Blog.

]]>

The programming language C stands as a key pillar in the world of computer science, remaining valuable even as the tech industry continues to evolve. Its flexibility, efficiency, and its influenceon many other languages make it a foundational skill for many developers, and a language of choice for system programming, embedded systems, and more

Having a firm grasp of C can open doors to numerous opportunities. It’s a language that often acts as a stepping stone to others, giving developers a more in-depth understanding of how computers really work. For instance, it provides first-hand experience with concepts like memory management, pointers, and low-level access to system resources that are abstracted away in many high-level languages. This proficiency in C can significantly improve programming capabilities overall, resulting in better code efficiency and optimization in whichever language you work in next.

But for those aspiring to ace a C programming interview, it’s essential to move beyond the basics. One must challenge their coding abilities and practice working on the types of problems likely to be encountered in an interview setting. Here, we’ll discuss the details of the C language, explain what a typical C interview looks like, and provide a series of challenging C interview questions to help you sharpen your skills and stand out. 

What is C?

Created in the early 1970s, C is a general-purpose language with features that allow developers to build programs operating directly on a physical machine’s level. Due to its low-level capabilities, C has been instrumental in writing system software, enabling the development of compilers, interpreters, operating systems, and database systems.

C’s syntax is simple, making the language easy to learn and use. However, don’t let the simplicity fool you. C’s low-level nature and access to memory management, combined with its simplicity, make it an efficient language for creating fast, compact programs.

A distinct feature of C is its ability to manipulate system hardware directly through the use of pointers. This characteristic makes it invaluable for applications that require high performance or that operate at a system level, such as creating desktop applications, game development, and implementing other programming languages.

What a C Programming Interview Looks Like

A C programming interview often involves a range of elements. While the specific format may vary from company to company, you can generally expect a combination of coding exercises, problem-solving questions, and conceptual discussions. 

In coding exercises, you’ll be tasked to write C programs or functions that solve a specific problem or perform a particular task. These challenges can range from data structure and algorithm problems to system-level tasks, reflecting the range of applications where C shines. It’s also not uncommon to face questions involving memory management or pointers, given their significance in C.

The problem-solving questions are aimed at assessing your logical thinking and approach to software design. You might be presented with a high-level problem and asked to outline how you’d tackle it using C. This could involve discussing the data structures you’d use, the algorithms you’d implement, and how you’d ensure your solution is efficient and robust.

Conceptual discussions focus on your understanding of C and its various constructs. You might be asked about how certain features of C work, like its memory management system, how pointers function, or the purpose of specific keywords. It’s crucial to not only know how to use C but to understand how it works behind the scenes.

C Interview Questions

In this section, we’ll dive into a series of C interview questions, starting from an intermediate level and getting progressively tougher. Remember, the goal isn’t to breeze through these questions, but to stretch your C programming skills and prepare you for the types of challenges you might encounter in a real-life interview.

1. Array Rotation

Task: Write a C function named ‘rotate’ that takes an array and its length as input and rotates the array in-place to the right by one position.

Input Format: The input will be an integer array and its length.

Constraints: The array length will be at least 1.

Sample Input: int arr[] = {1, 2, 3, 4, 5}; int n = 5;

Array after rotation: 5 1 2 3 4

Sample Code:

void rotate(int arr[], int n) {

   int temp = arr[n-1], i;

   for (i = n-1; i > 0; i--)

      arr[i] = arr[i-1];

   arr[0] = temp;

}

Explanation: 

The ‘rotate’ function temporarily stores the last array element to prevent data loss during the shifts. Next, using a for loop, it moves all the elements one step to the right. Finally, it places the saved element at the array’s start, completing the rotation.

This question tests the candidate’s ability to work with arrays and manipulate them, a fundamental skill in C programming. It mimics real-world scenarios where developers often need to shift, rotate or rearrange data stored in arrays. 

2. String Palindrome

Task: Write a C function named ‘isPalindrome’ that checks whether a given string is a palindrome or not.

Input Format: The input will be a string.

Constraints: The string will only contain alphanumeric characters.

Output Format: The function should return 1 if the string is a palindrome and 0 otherwise.

Sample Input: racecar

Sample Output: 1

Sample Code:

int isPalindrome(char* str) {

    int l = 0;

    int h = strlen(str) - 1;

 

    while (h > l)

    {

        if (str[l++] != str[h--])

        {

            return 0;

        }

    }

    return 1;

}

Explanation:

The ‘isPalindrome’ function first finds the length of the string and sets two pointers, one at the start (l) and one at the end (h). It then compares the characters at the positions pointed by ‘l’ and ‘h’. If they are not the same, it returns 0, indicating that the string is not a palindrome. If they are the same, it increments ‘l’ and decrements ‘h’ and repeats the comparison until ‘h’ is less than ‘l’, at which point it returns 1, confirming that the string is a palindrome.

This question tests a candidate’s understanding of string manipulation and comparison, fundamental tasks in many real-world applications. Well-crafted solutions demonstrate the candidate’s proficiency with string operations and working with pointers in C.

3. Linked List Reversal

Task: Write a C function called ‘reverseList’ that reverses a linked list.

Input Format: The input will be a pointer to the head of a singly linked list.

Sample Input: 1 -> 2 -> 3 -> 4 -> NULL

Linked list after rotation: 4 -> 3 -> 2 -> 1 -> NULL

Sample Code:

typedef struct Node {

    int data;

    struct Node* next;

} Node;




void reverseList(Node** head_ref) {

    Node* prev   = NULL;

    Node* current = *head_ref;

    Node* next = NULL;

    while (current != NULL) {

        next  = current->next;  

        current->next = prev;   

        prev = current;

        current = next;

    }

    *head_ref = prev;

}

Explanation:

The ‘reverseList’ function reverses a linked list by reassigning the ‘next’ pointers of each node. It iterates through the linked list, starting at the head, and in each iteration, it reassigns the ‘next’ pointer of the current node to the previous node. After each iteration, it moves to the next node by following the original ‘next’ pointer, which it saved before reassignment. When it reaches the end of the list, it assigns the ‘prev’ node as the new head of the linked list.

This question tests a candidate’s proficiency with pointers and dynamic memory allocation, and their understanding of complex data structures like linked lists, skills often necessary when working with C in system-level programming.

Explore verified tech roles & skills.

The definitive directory of tech roles, backed by machine learning and skills intelligence.

Explore all roles

4. Calculate the Nth Term

This challenge will help you test your understanding of recursion.

A function that calls itself is known as a recursive function. The C programming language supports recursion. But while using recursion, one needs to be careful to define an exit condition from the function, otherwise it will go into an infinite loop.

To prevent infinite recursion, an ‘if…else’ statement (or a similar approach) can be used where one branch makes the recursive call and the other doesn’t.

void recurse() {

    .....

    recurse()  //recursive call

    .....

}

int main() {

    .....

    recurse(); //function call

    .....

}

Task: There is a series, ‘S’, where the next term is the sum of previous three terms. Given the first three terms of the series, ‘a’, ‘b’, and ‘c’ respectively, you have to output the nth term of the series using recursion.

Input Format: The first line contains a single integer, ‘n’. The next line contains 3 space-separated integers, ‘a’, ‘b’, and ‘c’.

Constraints:

  • 1 ≤ n ≤ 20
  • 1 ≤ a,b,c ≤ 100

Output Format: Print the nth term of the series, S(n).

Sample Input:

5

1 2 3

Sample Output: 11

Explanation:

Consider the following steps:

  1. S(1) = 1
  2. S(2) = 2
  3. S(3) = 3
  4. S(4) = S(3) + S(2) + S(1)
  5. S(5) = S(4) + S(3) + S(2)

From steps 1, 2, 3, and 4, we can say S(4) = 3 + 2 + 1 = 6; then using the values from step 2, 3, 4, and 5, we get S(5) = 6 + 3 + 2 = 11. Thus, we print 11 as our answer.

Solve the problem.

5. Implementing a Stack

Task: Write a C program to implement a stack using a linked list. Your program should have ‘push’ and ‘pop’ operations.

Input Format: The inputs will be the elements to be pushed to the stack.

Output Format: The outputs will be the elements popped from the stack.

Sample Input: push(1), push(2), push(3), pop(), pop()

Sample Output: 3, 2

Sample Code:

typedef struct Node {

    int data;

    struct Node* next;

} Node;




Node* top = NULL;




void push(int data) {

    Node* newNode = (Node*)malloc(sizeof(Node));

    if (!newNode) {

        printf("Heap overflow");

        exit(1);

    }

    newNode->data = data;

    newNode->next = top;

    top = newNode;

}




int pop() {

    Node* temp;

    int poppedValue;




    if (top == NULL) {

        printf("Stack underflow");

        exit(1);

    }

    else {

        temp = top;

        top = top->next;

        poppedValue = temp->data;

        free(temp);

        return poppedValue;

    }

}

Explanation:

The given code demonstrates the implementation of a stack data structure in C using a singly linked list. The ‘push’ function creates a new node, checks if memory allocation was successful, and if so, assigns the input data to the new node and adds it to the top of the stack. The ‘pop’ function checks if the stack is empty and if it isn’t, removes the topmost node from the stack, returns its value, and frees the memory allocated to it.

This question tests a candidate’s understanding of fundamental data structures (like stacks) and their implementation in C, along with the use of dynamic memory allocation. Successfully tackling this problem demonstrates proficiency in handling memory, managing pointers, and understanding the lifecycles and behaviors of data structures, which are crucial for low-level and system programming tasks in C.

6. Binary Tree Traversal

Task: Write a C function named ‘inorderTraversal’ that performs an in-order traversal of a binary tree.

Input Format: The input will be a pointer to the root node of a binary tree.

Output Format: The function should print the nodes of the binary tree in an in-order traversal sequence.

Sample Input: Binary tree with nodes arranged as follows: 1 (root), 2 (left child of 1), 3 (right child of 1)

Sample Output: 2, 1, 3

Sample Code:

typedef struct Node {

    int data;

    struct Node* left;

    struct Node* right;

} Node;




void inorderTraversal(Node* root) {

    if (root != NULL) {

        inorderTraversal(root->left);

        printf("%d ", root->data);

        inorderTraversal(root->right);

    }

}

Explanation:

The ‘inorderTraversal’ function uses recursion to traverse a binary tree in in-order fashion, which means visiting the left subtree, the root node, and then the right subtree. If the given root node is not null, the function recursively calls itself to visit the left subtree, then it prints the root’s data, and finally, it calls itself again to visit the right subtree.

This question tests a candidate’s understanding of binary trees and their traversals, along with the concept of recursion. It’s a commonly asked question in C interviews because these are fundamental concepts often utilized in many computer science problems. 

7. Hash Table Implementation

Task: Write a C program to implement a simple hash table. This hash table will use chaining to handle collisions.

Input Format: The input will be the keys and values to be inserted in the hash table.

Output Format: The program should be able to retrieve values given the keys.

Sample Code:

#include <stdlib.h>

#include <string.h>




typedef struct node {

    char* key;

    char* value;

    struct node* next;

} node;




typedef struct hashtable {

    int size;

    struct node** table;

} hashtable;




hashtable* createHashtable(int size) {

    hashtable* newTable;

    if (size < 1) return NULL;

    if ((newTable = malloc(sizeof(hashtable))) == NULL) {

        return NULL;

    }

    if ((newTable->table = malloc(sizeof(node*) * size)) == NULL) {

        return NULL;

    }

    int i;

    for (i = 0; i < size; i++) {

        newTable->table[i] = NULL;

    }

    newTable->size = size;

    return newTable;

}




unsigned int hash(hashtable* hashtable, char* key) {

    unsigned int hashval = 0;

    for (; *key != '\0'; key++) {

        hashval = *key + (hashval << 5) - hashval;

    }

    return hashval % hashtable->size;

}




node* createNode(char* key, char* value) {

    node* newNode;

    if ((newNode = malloc(sizeof(node))) == NULL) {

        return NULL;

    }

    newNode->key = strdup(key);

    newNode->value = strdup(value);

    newNode->next = NULL;

    return newNode;

}




void set(hashtable* hashtable, char* key, char* value) {

    unsigned int bin = hash(hashtable, key);

    node* newNode = createNode(key, value);

    newNode->next = hashtable->table[bin];

    hashtable->table[bin] = newNode;

}




char* get(hashtable* hashtable, char* key) {

    unsigned int bin = hash(hashtable, key);

    node* pair = hashtable->table[bin];

    while (pair != NULL && pair->key != NULL) {

        if (strcmp(pair->key, key) == 0) {

            return pair->value;

        }

        pair = pair->next;

    }

    return NULL;

}

Explanation:

The provided code demonstrates the implementation of a simple hash table with chaining in C. It includes the creation of a hash table, generation of hash values from keys, and insertion and retrieval of key-value pairs. The hash table uses a simple hash function to convert keys into indices. If collisions occur (when different keys result in the same index), chaining is used by maintaining a linked list of key-value pairs for each index in the hash table.

This question is challenging because it involves various crucial concepts in C: dynamic memory allocation, pointers, linked lists, and data structures. Hash tables are widely used due to their efficiency in key-value pair storage and retrieval. 

Resources to Improve C Knowledge

This article was written with the help of AI. Can you tell which parts?

The post 7 C Interview Questions Every Developer Should Know appeared first on HackerRank Blog.

]]>
https://www.hackerrank.com/blog/7-c-interview-questions-every-developer-should-know/feed/ 0
8 PHP Interview Questions Every Developer Should Know https://www.hackerrank.com/blog/php-interview-questions-every-developer-should-know/ https://www.hackerrank.com/blog/php-interview-questions-every-developer-should-know/#respond Fri, 07 Jul 2023 12:45:19 +0000 https://www.hackerrank.com/blog/?p=18905 The world of software development evolves at a dizzying pace. Yet it is the oldest...

The post 8 PHP Interview Questions Every Developer Should Know appeared first on HackerRank Blog.

]]>
Abstract, futuristic image generated by AI

The world of software development evolves at a dizzying pace. Yet it is the oldest programming languages that continue to make the biggest impact. One such language that has consistently held its ground is PHP. Created in 1994, it’s the backbone of 77.4 percent of all websites with a known server-side programming language, highlighting its profound influence on the internet’s infrastructure. 

This widespread usage of PHP in various domains opens up a world of opportunities, leading to a growing demand for proficient PHP developers. However, with high demand comes high standards. Companies are on the lookout for professionals who can tackle complex problems, write efficient code, and effectively manage and manipulate data. Understanding the nuances of PHP, therefore, becomes a valuable skill, both for developers seeking to showcase their PHP prowess and for recruiters intent on hiring the best talent.

This post will dive into some PHP essentials and guide you through a series of progressively challenging PHP interview questions, providing illustrative code snippets and clear explanations to help you tackle your next PHP interview with confidence.

What is PHP?

PHP, an acronym for “Hypertext Preprocessor”, is a widely-used, open-source scripting language. It was specially designed for web development but is also used as a general-purpose programming language. PHP scripts are primarily used on the server side, meaning they run on the web server. It’s a robust platform for creating dynamic and interactive websites and web applications, which is part of what makes it so prevalent across the web.

The beauty of PHP lies in its flexibility. It can be embedded directly within HTML code, eliminating the need for calling an external file to process data. It also integrates seamlessly with various databases such as MySQL, Oracle, and Microsoft SQL Server. Plus, it’s compatible with most web servers and runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.), providing developers with extensive versatility.

Given its server-side scripting prowess, PHP is typically used to perform operations like form data collection, file handling on the server, session tracking, or even building entire e-commerce websites. This wide range of applications explains why PHP skills are sought after for various technical roles.

What a PHP Interview Looks Like

The PHP interview process varies between organizations, but a few constants provide a broad picture of what to expect. These interviews are designed to assess a candidate’s understanding of PHP as a language, its applications, problem-solving skills, and sometimes their experience with PHP-based frameworks like Laravel or Symfony.

One of the first things to note is that PHP interviews often involve several layers. Typically, there’s an initial screening to evaluate the candidate’s basic PHP knowledge and possibly some related technologies like SQL or JavaScript. Following that, there’s usually a technical interview that delves deeper into PHP concepts and problem-solving skills.

A significant component of the technical interview is the coding challenge. These challenges test the ability of a candidate to apply their knowledge to solve real-world problems. They can range from simple tasks like string manipulation to more complex problems such as creating a simple CRUD (Create, Retrieve, Update, Delete) application or working with APIs.

The type of roles that require PHP skills vary widely but most commonly include web development roles. Web developers, particularly back-end developers, are often expected to have a solid understanding of PHP to create dynamic web pages or web applications. Other roles like software engineers might also need to know PHP, especially if they’re working on web-based applications. 

Even certain database administrator roles might require PHP knowledge, as PHP is commonly used to interact with databases. Additionally, since PHP can be used as a general-purpose scripting language, it could also come in handy for system administrators.

PHP Interview Questions

The complexity and depth of PHP interview questions can range widely, depending on the specific role and level of expertise required. This section will explore a progressive series of PHP coding challenges that span intermediate to advanced proficiency. These questions will serve as a vital resource for developers seeking to sharpen their skills or for hiring teams aiming to evaluate candidate competencies effectively.

1. Array Manipulation

Task: Write a PHP function called findMissingNumber that takes an array of consecutive numbers as input and returns the missing number.

Input Format: The input will be an array of integers.

Constraints:

  • The array will contain consecutive integers, with one integer missing.
  • The array will have at least two elements.

Output Format: The output will be an integer.

Sample Input: [1, 2, 4, 5, 6]

Sample Output: 3

Sample Code:

function findMissingNumber($numbers) {
    $count = count($numbers);
    $total = (($count + 1) * ($count + 2)) / 2;
    $sum = array_sum($numbers);
    return $total - $sum;
}
print_r(findMissingNumber(array(1, 2, 4, 5, 6)));

Explanation: 

The function first calculates the total sum of what the numbers would be if none were missing. Then it calculates the sum of the given numbers. The difference between these two sums is the missing number. This question tests the candidate’s ability to use built-in PHP functions for array manipulation and mathematical computations.

2. Handling Exceptions and Working with Files

Task: Write a PHP function called readFileAndSumNumbers that reads a file with numbers (one number per line), parses the numbers, and returns their sum.

Input Format: The input will be a string representing the path to the file.

Constraints:

  • The file will contain at least one number.
  • The file may contain empty lines or lines with non-numeric characters.
  • Each number will be an integer.

Output Format: The output will be an integer representing the sum of all numbers in the file. If a line cannot be parsed as a number, it should be ignored.

Sample Input: “numbers.txt” (file content: 1\n2\n3\nfoo\n4\n5\nbar\n)

Sample Output: 15

Sample Code:

function readFileAndSumNumbers($filePath) {
    $sum = 0; 
    try {
        $file = new SplFileObject($filePath);       
        while (!$file->eof()) {
            $line = $file->fgets();           
            if (is_numeric($line)) {
                $sum += (int)$line;
            }
        }
    } catch (Exception $e) {
        echo "An error occurred: " . $e->getMessage();
    }
    return $sum;
}
echo readFileAndSumNumbers("numbers.txt");

Explanation:

The readFileAndSumNumbers function starts by defining a sum variable to hold the total sum of the numbers. It then attempts to read each line from the file.

The is_numeric() function is used to check if each line can be treated as a number. If it can, the line is cast to an integer and added to the sum. If not, the line is ignored.

If an exception occurs during the execution of the code (such as a RuntimeException if the specified file doesn’t exist), the exception is caught and an error message is printed. Regardless, the function returns the sum of the parsed numbers.

This question tests a candidate’s ability to handle exceptions and work with files in PHP. It also provides an opportunity to demonstrate understanding of PHP’s type checking and casting mechanisms.

3. Regular Expressions

Task: Write a PHP function called isValidEmail that takes a string as input and uses a regular expression to verify if it is a valid email address. 

Input Format: The input will be a string.

Constraints: The string will contain at least one character.

Output Format: The output will be a boolean. Return true if the string is a valid email address and false otherwise.

Sample Input: test@example.com

Sample Output: true

Sample Code:

function isValidEmail($email) {
    return (filter_var($email, FILTER_VALIDATE_EMAIL)) ? true : false;
}
echo isValidEmail('test@example.com') ? 'Valid' : 'Invalid';

Explanation:

The isValidEmail function uses PHP’s built-in filter_var function with the FILTER_VALIDATE_EMAIL filter to validate the email address. If the email is valid, the function returns true; if it’s not, it returns false.

This question tests a candidate’s understanding of PHP’s built-in functions and ability to handle string validation tasks that are common in real-world applications.

4. Object-Oriented Programming

Task: Define a PHP class called Circle, with a private property radius. Add a constructor to set the radius and two public methods: getArea and getCircumference to calculate the area and the circumference of the circle, respectively.

Sample Code:

class Circle {
    private $radius;
    public function __construct($radius) {
        $this->radius = $radius;
    }
    public function getArea() {
        return pi() * pow($this->radius, 2);
    }
    public function getCircumference() {
        return 2 * pi() * $this->radius;
    }
}
$circle = new Circle(5);
echo "Area: " . $circle->getArea();
echo "\nCircumference: " . $circle->getCircumference();

Explanation:

The Circle class is defined with a private property radius. The constructor method takes radius as a parameter and assigns it to the radius property. 

Two public methods, getArea and getCircumference, are defined to calculate the area and circumference of the circle. They use the pi() function to get the value of π, and pow() to calculate the square of the radius. 

This question tests a candidate’s understanding of object-oriented programming concepts in PHP, such as classes, properties, methods, and constructors.

Explore verified tech roles & skills.

The definitive directory of tech roles, backed by machine learning and skills intelligence.

Explore all roles

5. Dealing with Databases

Task: Write a PHP function called fetchUsers that connects to a MySQL database, fetches all records from the users table, and returns the result as an array.

Sample Code:

function fetchUsers($hostname, $username, $password, $dbname) {
    // Create connection
    $conn = new mysqli($hostname, $username, $password, $dbname);  
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    $sql = "SELECT * FROM users";
    $result = $conn->query($sql);
    $users = [];
    while($row = $result->fetch_assoc()) {
        $users[] = $row;
    }
   $conn->close();
    return $users;
}

Explanation:

The fetchUsers function first creates a new MySQLi object and establishes a connection with the MySQL database using the provided hostname, username, password, and database name. 

It then constructs a SQL query to fetch all records from the users table. The query is executed using the query() method of the MySQLi object. 

The function iterates over the result set using a while loop and the fetch_assoc() method, which fetches a result row as an associative array. Each row is added to the users array. 

Once all rows have been fetched, the database connection is closed using the close() method of the MySQLi object. 

This question tests the candidate’s understanding of PHP’s MySQLi extension, which allows PHP to access and manipulate MySQL databases, and their ability to interact with databases using SQL.

6. Design Patterns

Task: Implement a Singleton design pattern in PHP.

Sample Code:

class Singleton {
    // Hold the class instance.
    private static $instance = null;
    // The constructor is private to prevent initiation with outer code.
    private function __construct() {}
    // The object is created from within the class itself only if the class has no instance.
    public static function getInstance() {
        if (self::$instance == null) {
            self::$instance = new Singleton();
        }
        return self::$instance;
    }
}

Explanation:

The Singleton class is a design pattern that restricts a class from instantiating multiple objects. It’s useful when only a single instance of a class is required to control actions. 

It’s implemented by creating a class with a method that creates a new instance of the class if one doesn’t exist. If an instance already exists, it simply returns a reference to that object. To prevent additional instantiation, the constructor is made private.

In the provided sample code, Singleton is a class with a private static variable $instance to hold the single instance of the class, a private constructor to prevent external instantiation, and a public static getInstance method to control the access to the single instance of the class.

This question tests a candidate’s understanding of design patterns in PHP, specifically the Singleton pattern. It requires a good understanding of object-oriented programming principles in PHP, including classes, methods, and variables visibility (public, private, protected), and static properties and methods.

7. Memory Management

Task: Write a PHP function called calculateMemoryUsage that takes a large array as an input, performs a certain operation on the array (like sorting it), and then calculates and returns the difference in memory usage before and after the operation.

Sample Code:

function calculateMemoryUsage($largeArray) {
    $startMemory = memory_get_usage();
    sort($largeArray);
    $endMemory = memory_get_usage();
    $memoryUsed = $endMemory - $startMemory;
    return $memoryUsed;
}

Explanation:

The calculateMemoryUsage function uses PHP’s memory_get_usage function to get the amount of memory, in bytes, that’s currently being used by the PHP script. 

It captures the memory usage at the start, performs an operation (in this case, sorting the array), and then captures the memory usage again at the end. The difference between the end and start memory usages is calculated and returned, representing the additional memory used by the operation.

This question is a good opportunity for candidates to demonstrate an understanding of how PHP manages memory and the impact of different operations on memory usage. It’s an important consideration for writing efficient, performant PHP code, especially when dealing with large data sets.

8. HTTP and Session Management

Task: Write a PHP script to start a new session, set a session variable, and then retrieve the value of that session variable.

Sample Code:

// Start the session
session_start();
// Set session variable
$_SESSION["favorite_color"] = "blue";
// Get session variable
$favoriteColor = $_SESSION["favorite_color"];

Explanation:

In this task, the PHP session_start function is first called to start a new session or to resume the current one. This is necessary before any session variables can be set.

Then, a session variable “favorite_color” is set to “blue” using the global $_SESSION variable, which is an associative array containing session variables available to the current script.

Finally, the value of the “favorite_color” session variable is retrieved and stored in the $favoriteColor variable.

This question tests a candidate’s understanding of HTTP, sessions, and how PHP manages state across different web requests. In a stateless protocol like HTTP, sessions provide a way to store information about a user across multiple requests. Mastery of session management is key to developing interactive and personalized web applications with PHP.

Resources for Interview Preparation

This article was written with the help of AI. Can you tell which parts?

The post 8 PHP Interview Questions Every Developer Should Know appeared first on HackerRank Blog.

]]>
https://www.hackerrank.com/blog/php-interview-questions-every-developer-should-know/feed/ 0
6 C# Interview Questions Every Developer Should Know https://www.hackerrank.com/blog/c-sharp-interview-questions-every-developer-should-know/ https://www.hackerrank.com/blog/c-sharp-interview-questions-every-developer-should-know/#respond Mon, 26 Jun 2023 16:52:22 +0000 https://www.hackerrank.com/blog/?p=18901 If you’ve ever stepped into a tech interview, you know it’s more than just a...

The post 6 C# Interview Questions Every Developer Should Know appeared first on HackerRank Blog.

]]>
Abstract, futuristic image generated by AI

If you’ve ever stepped into a tech interview, you know it’s more than just a test — it’s a performance. Your task? To demonstrate your problem-solving prowess, your adaptability, and your deep well of knowledge in your field, all under the watchful eyes of your potential future employers. When it comes to demonstrating your C# expertise, you’re not only showing your understanding of the language but also your ability to apply that knowledge effectively under interview pressures. 

With C# being one of the most popular languages for developing Windows desktop applications and games, the demand for skilled C# developers is high. It’s the fourth most in-demand language in job posts that explicitly require specific programming language skills. And employers are becoming increasingly thorough with their interviewing process. The coding interview is your chance to shine. Hence, it’s crucial not just to know C# but also to be able to apply the concepts under the constraints of an interview.

In this guide, you will find key C# interview questions that range from intermediate to advanced levels. These questions are designed to test a variety of your C# skills, with each one focusing on a different aspect of the language. By the time you’re done with this guide, you’ll not only have a deeper understanding of C#, but also be well prepared to handle even the toughest C# interview questions.

Understanding C# Programming

C#  — pronounced “C-Sharp” — is a modern, general-purpose programming language developed by Microsoft as part of its .NET initiative. As a language, C# is object-oriented, statically typed, and built on the syntax and semantics of C and C++, making it familiar and relatively easy to learn for anyone with a background in these languages.

Why does C# matter, you ask? Well, it’s all about its power and versatility. C# is the go-to language for developing Windows desktop applications and games, thanks to the powerful .NET framework that supports it. From creating sophisticated user interfaces to handling complex business logic, C# provides developers with the tools they need to build robust and scalable applications.

One of the notable features of C# is its strong type system, which reduces runtime errors and improves code maintainability. C# also supports features like automatic garbage collection, exception handling, and LINQ (Language Integrated Query) that can make your code cleaner and more efficient.

Additionally, the rise of Unity, a popular game engine that uses C#, has bolstered the demand for C# developers in the gaming industry. As the language continues to evolve, so too do the opportunities for those who master it.

What a C# Interview Looks Like

Stepping into a C# interview can be a unique experience. While every company has its own interviewing style, there are some common patterns you’re likely to encounter.

In a typical C# interview, expect a blend of conceptual, problem-solving, and coding questions. The conceptual questions test your theoretical knowledge and understanding of C# and its surrounding ecosystem (.NET, ASP.NET, etc.). For instance, you might be asked to explain the difference between a struct and a class in C#, or describe how garbage collection works in the .NET runtime.

Problem-solving questions are where you get to shine as a software engineer. These usually revolve around algorithms and data structures, requiring you to devise and articulate a solution to a problem. While these aren’t always C# specific, you’ll need to demonstrate proficiency in using C# constructs to implement your solution.

Lastly, the coding questions. These are your opportunity to show off your practical C# skills. You might be asked to write a piece of code on a whiteboard, on paper, or in a shared online editor. These questions might involve building a small feature, fixing a bug, or even reviewing a piece of existing code.

When it comes to technical roles requiring C# skills, there’s a wide range. Software developers, back-end developers, game developers, and even test engineers might all be required to demonstrate their proficiency in C#. And it’s not limited to these roles. As more and more industries embrace digital transformation, the need for C# skills is expanding into fields like data analysis, machine learning, and more.

C# Interview Questions

The key to navigating a C# interview successfully is to prepare well. Understand the concepts, practice problem-solving, and, most importantly, write code. Regular, hands-on coding practice is crucial. To help you with that, we’re going to look at some common C# interview questions. From intermediate to advanced, these questions cover a range of topics and coding challenges that you’re likely to encounter in a real-world C# interview. 

1. Using LINQ for Filtering and Sorting Data

This question tests your understanding and application of LINQ (Language Integrated Query), a powerful feature in C# that is used for working with data.

Task: Write a C# method called FilterAndSort that takes a list of students (objects) and returns a sorted list of student names who have a GPA greater than 3.5. The list should be sorted in descending order.

Input Format: The input will be a List<Student>, where the Student class is defined as follows:

public class Student
{
    public string Name { get; set; }
    public double GPA { get; set; }
}

Constraints:

  • The list will contain at least one Student object.
  • Student names will be non-empty strings.
  • GPA will be a double between 0.0 and 4.0.

Output Format: The output will be a List<string> containing the names of students who have a GPA greater than 3.5, sorted in descending order.

Sample Input:

var students = new List<Student>
{
    new Student { Name = "Alice", GPA = 3.6 },
    new Student { Name = "Bob", GPA = 3.2 },
    new Student { Name = "Charlie", GPA = 3.8 }
};

Sample Output: [“Charlie”, “Alice”]

Sample Code:

public static List<string> FilterAndSort(List<Student> students)
{
    return students
        .Where(student => student.GPA > 3.5)
        .OrderByDescending(student => student.GPA)
        .Select(student => student.Name)
        .ToList();
}

Explanation:

The FilterAndSort method utilizes several LINQ operators to filter and sort the list of students. 

First, the Where operator is used to filter out students who have a GPA greater than 3.5. 

Then, the OrderByDescending operator is used to sort the remaining students in descending order based on their GPA.

The Select operator is then used to project each student into a new form — in this case, just their name.

Finally, ToList is called to convert the resulting IEnumerable to a list.

This question is excellent for testing your understanding of how to use LINQ to manipulate data in C#. In an interview setting, it can also lead to further discussions about performance considerations and alternative approaches. 

2. Handling Exceptions

Exception handling is a critical part of robust application development. This question tests your understanding of I/O operations, string parsing, error checking, and of course, exception handling in C#.

Task: Write a C# method called ReadFileAndSumNumbers that reads a file with numbers (one number per line), parses the numbers, and returns their sum.

Input Format: The input will be a string representing the path to the file.

Constraints:

  • The file will contain at least one number.
  • The file may contain empty lines or lines with non-numeric characters.
  • Each number will be an integer.

Output Format: The output will be an integer representing the sum of all numbers in the file. If a line cannot be parsed as a number, it should be ignored.

Sample Input: “numbers.txt” (file content: ‘1\n2\n3\nfoo\n4\n5\nbar\n’)

Sample Output: 15

Sample Code:

public static int ReadFileAndSumNumbers(string filePath)
{
    int sum = 0;
 
    try
    {
        foreach (var line in File.ReadLines(filePath))
        {
            if (int.TryParse(line, out int number))
            {
                sum += number;
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"An error occurred: {ex.Message}");

    }
    return sum;
}

Explanation:

The ReadFileAndSumNumbers method starts by defining a sum variable to hold the total sum of the numbers. It then attempts to read each line from the file.

The TryParse method is used to attempt to parse each line as an integer. If the parsing is successful, the parsed number is added to the sum. If not, the line is ignored.

If an exception occurs during the execution of the code (such as a FileNotFoundException if the specified file doesn’t exist), the exception is caught and an error message is displayed. Regardless, the method returns the sum of the parsed numbers.

This question assesses your ability to write robust C# code that can handle unexpected input and recover gracefully from errors. It’s also a good opportunity to demonstrate your knowledge of .NET’s I/O and exception-handling capabilities. 

3. Implementing a Singleton Pattern

The Singleton is a design pattern that restricts the instantiation of a class to a single instance and provides a global point of access to it. This question will test your understanding of object-oriented programming and design patterns in C#.

Task: Implement a thread-safe Singleton class in C#.

Constraints: The Singleton class should be designed in such a way that only a single instance of the class can exist in the application, and this instance should be accessible globally.

Sample Code:

public sealed class Singleton

{

    private static Singleton instance = null;
    private static readonly object padlock = new object();
    Singleton()
    {
    }
    public static Singleton Instance
    {
        get

        {
            lock (padlock)
            {
                if (instance == null)
                {
                    instance = new Singleton();
                }
                return instance;
            }
        }
    }
}

Explanation:

The Singleton class is defined as sealed to prevent derivation, which could add instances.

A private, read-only padlock object is defined. This is used for thread synchronization to ensure that only one thread can enter the lock code block at a time. This is important because, without thread safety, two threads could create two separate instances of the Singleton class.

The constructor of the Singleton class is defined as private to prevent instantiation from outside the class.

Inside the Instance property, if the Singleton instance is null, a new Singleton object is created and assigned to the instance variable. If the Singleton instance already exists, the existing instance is returned.

This question checks your understanding of object-oriented programming, specifically Singleton design pattern. Singleton is one of the Gang of Four design patterns and is categorized under creational design patterns as it deals with object creation mechanisms.

Explore verified tech roles & skills.

The definitive directory of tech roles, backed by machine learning and skills intelligence.

Explore all roles

4. Asynchronous Programming with Tasks

Asynchronous programming is a form of parallel programming that allows a unit of work to run separately from the primary application thread. It’s a powerful tool for creating responsive, efficient applications. This question will test your understanding of tasks, an essential part of asynchronous programming in C#.

Task: Write a C# method called DownloadFileAsync that downloads a file from a given URL and saves it to a specified path. The method should be asynchronous and return the size of the downloaded file.

Input Format: Two strings: the first represents the URL of the file to download, and the second represents the path to save the file.

Output Format: The output will be a Task<long>, representing the size of the downloaded file in bytes.

Constraints:

  • The URL will be a valid URL to a file.
  • The path will be a valid file path.

Sample Code:

public static async Task<long> DownloadFileAsync(string url, string path)

{
    using (var httpClient = new HttpClient())
    {
        var response = await httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
        using (var fileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None))
        {
            await response.Content.CopyToAsync(fileStream);
            return fileStream.Length;
        }
    }
}

Explanation:

The DownloadFileAsync method starts by creating a HttpClient object, which is used to send HTTP requests and receive HTTP responses from a resource identified by a URI.

httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead) is used to send a GET request to the specified URI and return the response. The await keyword is used to suspend the execution of the method until the awaited task completes, without blocking the main thread. The HttpCompletionOption.ResponseHeadersRead enum value indicates that the operation should complete as soon as a response is available and headers are read. The response body is read at a later time.

Then a FileStream object is created to write the file data to the specified path. The await keyword is again used when copying the content of the response to the file stream.

Finally, the size of the downloaded file is returned.

This question tests your understanding of asynchronous programming, which is essential for creating responsive applications in C#. It can also lead to further discussions about handling large files, error checking, and more.

5. Understanding ASP.NET Core Middleware

ASP.NET Core middleware components are pieces of code that handle requests and responses. They form the Request Pipeline, which is used to process all requests and responses. This question will test your understanding of middleware in ASP.NET Core.

Task: Write an ASP.NET Core middleware that logs the time taken for each request to be processed.

Constraints: The middleware should log the start time and end time for each request, and the time taken to process the request.

Sample Code:

public class RequestTimingMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger _logger;
    public RequestTimingMiddleware(RequestDelegate next, ILogger<RequestTimingMiddleware> logger)
    {
        _next = next;
        _logger = logger;
    }
    public async Task InvokeAsync(HttpContext context)
    {
        var startTime = DateTime.UtcNow;
        _logger.LogInformation($"Request started at {startTime}");
        await _next(context);
        var endTime = DateTime.UtcNow;
        _logger.LogInformation($"Request ended at {endTime}");
        _logger.LogInformation($"Request processed in {endTime - startTime}");
    }
}

Explanation:

This piece of middleware starts by logging the start time of the request. It then calls the next middleware in the pipeline by invoking _next(context). After the next middleware has completed, it logs the end time of the request and the total time taken to process the request.

The middleware is implemented as a class with a constructor that takes a RequestDelegate and an ILogger. The RequestDelegate represents the next middleware in the pipeline, and the ILogger is used to log information.

InvokeAsync is the method that ASP.NET Core automatically calls to execute the middleware. In this case, it logs the time before and after the execution of the next middleware in the pipeline.

This question tests your understanding of ASP.NET Core middleware and how requests are processed. It’s also a good opportunity to discuss how logging can help diagnose and troubleshoot issues in your applications.

6. Working with Entity Framework Core

Entity Framework Core is an open-source, lightweight, extensible, and cross-platform version of Entity Framework data access technology. This question will test your understanding of Entity Framework Core and its query capabilities.

Task: Write a method called GetOverdueBooks using Entity Framework Core that retrieves a list of books that were due to be returned more than 30 days ago from a library database.

Input Format: The method takes no arguments.

Output Format: The method returns a List<Book>, where Book is a class representing a book in the library.

Constraints:

  • A Book class exists with properties Title (string), DueDate (DateTime), and other properties as necessary.
  • A LibraryContext class exists that extends DbContext and includes a DbSet<Book> Books.

Sample Code:

public List<Book> GetOverdueBooks()
{
    using (var context = new LibraryContext())
    {
        var overdueBooks = context.Books
            .Where(b => b.DueDate < DateTime.Now.AddDays(-30))
            .ToList();
        return overdueBooks;
    }
}

Explanation:

The GetOverdueBooks method starts by creating an instance of LibraryContext, which is our Entity Framework database context. 

The LINQ query context.Books.Where(b => b.DueDate < DateTime.Now.AddDays(-30)) is used to retrieve all books whose DueDate is more than 30 days ago. Note the use of DateTime.Now.AddDays(-30), which calculates the date 30 days ago.

Finally, the method calls ToList to execute the query and convert the results to a list of Book objects, which is returned.

This question tests your knowledge of Entity Framework Core and its ability to perform complex queries against a database using LINQ. Understanding how to work with databases is essential for most back-end roles.

Resources to Improve C# Knowledge

This article was written with the help of AI. Can you tell which parts?

The post 6 C# Interview Questions Every Developer Should Know appeared first on HackerRank Blog.

]]>
https://www.hackerrank.com/blog/c-sharp-interview-questions-every-developer-should-know/feed/ 0
7 TypeScript Interview Questions Every Developer Should Know https://www.hackerrank.com/blog/typescript-interview-questions-developers-should-know/ https://www.hackerrank.com/blog/typescript-interview-questions-developers-should-know/#respond Wed, 21 Jun 2023 12:45:15 +0000 https://www.hackerrank.com/blog/?p=18833 In the wide world of JavaScript development, TypeScript has made a name for itself by...

The post 7 TypeScript Interview Questions Every Developer Should Know appeared first on HackerRank Blog.

]]>
Abstract, futuristic image generated by AI

In the wide world of JavaScript development, TypeScript has made a name for itself by improving upon the scalability, maintainability, and reliability of JavaScript. Now, more than 10 years after its release, it’s everywhere — from top-notch tech companies to the tiniest startups. TypeScript has been gaining in popularity over the last few years, and it seems like the upward trajectory is only going to continue. In our 2023 Developer Skills Report, we saw demand for TypeScript assessments explode by 2,788 percent in 2022, growing faster both in terms of popularity and demand than any other programming language.

So, what does this mean for developers? Opportunity. There’s a surge of demand for TypeScript developers, and if you can show that you have a solid understanding of this versatile superset of JavaScript, it can open many doors. But, as with all things, to seize these opportunities, you need to be prepared. This blog post will help you understand the kind of TypeScript interview questions that might come your way and help you prepare for and answer them with confidence. 

What is TypeScript?

TypeScript, as its name suggests, is all about types. At its core, TypeScript is a statically typed superset of JavaScript that compiles to plain JavaScript. It was developed by Microsoft in 2012 with the aim to make JavaScript development more efficient and less error-prone.

Being a superset means that any valid JavaScript code is also valid TypeScript code. However, TypeScript adds a powerful feature not present in standard JavaScript: static types. With TypeScript, you can declare types for your variables, function parameters, and object properties. This provides a level of certainty about the kind of data your code will be dealing with, which can be a huge boon for debugging and catching errors at compile-time, rather than at run-time.

What a TypeScript Interview Looks Like

Understanding what a TypeScript coding interview may entail is the first step toward acing it. Just like any other technical interview, a TypeScript interview will test your understanding of concepts, your problem-solving skills, and your ability to apply those skills to real-world scenarios.

Typically, TypeScript coding interviews will focus on the following areas:

  • Understanding of TypeScript Basics: You will be expected to know the basics, such as how to define and use types, interfaces, enums, and generics.
  • TypeScript Features: Questions may probe your knowledge of TypeScript’s unique features like static types, type inference, and type guards.
  • Integration with JavaScript Ecosystem: TypeScript plays well with the JavaScript ecosystem, so you may be asked about integrating TypeScript with popular JavaScript frameworks like Angular, React, or Vue.js.
  • Real-World Problem Solving: Practical coding exercises where you’ll need to solve a problem or build a small feature using TypeScript.
  • Best Practices: You should also be aware of best practices when it comes to using TypeScript — things like when and how to use “any” or “unknown” types, how to avoid null and undefined errors, and how to use optional chaining and nullish coalescing.

But who might be interested in your TypeScript skills? Many technical roles require TypeScript expertise, including front-end developers, full-stack developers, back-end developers, and web application developers. These roles span companies of all sizes and industries of all types, providing experienced TypeScript developers with a number of opportunities to flex their skills.

1. TypeScript Function Overloading

Function overloading is an important aspect of TypeScript that offers the flexibility to create functions with the same name but different arguments or return types. This is a common practice in many strongly typed languages.

Task: Write a TypeScript function named process that accepts either a string or an array of strings. If the argument is a string, return it in uppercase; if it’s an array, return the array length.

Sample Code:

function process(input: string): string;

function process(input: string[]): number;

function process(input: any): any {

    if (typeof input === "string") {

        return input.toUpperCase();

    } else {

        return input.length;

    }

}

console.log(process("TypeScript")); // returns "TYPESCRIPT"

console.log(process(["JavaScript", "TypeScript"])); // returns 2

Explanation: The process function uses TypeScript’s type checking (typeof input === “string”) to determine the type of the input. If it’s a string, it uses the toUpperCase() method to return the uppercase version of the string. If the input is an array (meaning it’s not a string), it simply returns the length of the array.

2. Implementing an Interface

In TypeScript, interfaces define a contract for classes and help in achieving strong typing. The class that implements an interface must provide an implementation for all its members.

Task: Create an interface IVehicle with properties make, model, and year. Then, create a class Car that implements IVehicle. The Car class should have a constructor to initialize the properties and a method getDetails that returns a string containing all the details of the car.

Sample Code:

interface IVehicle {

    make: string;

    model: string;

    year: number;

}

class Car implements IVehicle {

    constructor(public make: string, public model: string, public year: number) {}

    getDetails(): string {

        return `${this.make} ${this.model} ${this.year}`;

    }

}

const myCar = new Car("Toyota", "Corolla", 2018);

console.log(myCar.getDetails()); // returns "Toyota Corolla 2018"

Explanation: The Car class constructor uses TypeScript’s shorthand for assigning parameters to class properties (public make: string). The getDetails method uses template literals (${this.make} ${this.model} ${this.year}) to format a string with the car details.

Explore verified tech roles & skills

Backed by machine learning and skills intelligence.

Explore all roles

3. Deep Equality Check

TypeScript, like JavaScript, treats objects as reference types, which means that two objects are considered equal only if they reference the exact same memory location. However, in many practical scenarios, we need to check if two objects have the same properties and values, regardless of whether they reference the same memory location or not. This is known as a deep equality check.

Task: Write a TypeScript function deepEqual that compares two objects for deep equality. The function should return true if the objects are deeply equal and false otherwise.

Sample Code:

type Value = number | string | boolean | null | Value[] | { [key: string]: Value };

function deepEqual(a: Value, b: Value): boolean {

    if (a === b) {

        return true;

    }

    if (typeof a === "object" && a !== null && typeof b === "object" && b !== null) {

        if (Object.keys(a).length !== Object.keys(b).length) {

            return false;

        }

        for (const key in a) {

            if (!b.hasOwnProperty(key) || !deepEqual(a[key], b[key])) {

                return false;
            }
        }

        return true;
    }

    return false;

}


console.log(deepEqual({ name: "John", age: 30 }, { name: "John", age: 30 })); // returns true

console.log(deepEqual({ name: "John", age: 30 }, { name: "John", age: 31 })); // returns false

Explanation: The deepEqual function uses recursion to perform a deep comparison of two objects. It first checks if the objects are the same using the strict equality operator (===). If not, it checks if both are objects (excluding null), then it compares the number of their properties (Object.keys(a).length !== Object.keys(b).length). If they have the same number of properties, it iteratively checks each property using the hasOwnProperty method and the deepEqual function itself.

4. Implementing a Decorator

Decorators provide a way to add both annotations and a meta-programming syntax for class declarations and members. They’re a stage 2 proposal for JavaScript and are widely used in TypeScript.

Task: Implement a class decorator @sealed that seals both the constructor and its prototype.

Sample Code:

function sealed(constructor: Function) {

    Object.seal(constructor);

    Object

.seal(constructor.prototype);

}

@sealed

class Greeter {

    greeting: string;

    constructor(message: string) {

        this.greeting = message;

    }

    greet() {

        return "Hello, " + this.greeting;

    }

}

Explanation: The @sealed decorator uses Object.seal, a JavaScript method that prevents new properties from being added to an object and marks all existing properties as non-configurable. This decorator can be used to ensure that a class and its prototype cannot be tampered with, which can be particularly useful when you need to guarantee that a class maintains its original behavior and structure.

5. Implement a Generic Class

In TypeScript, working with classes often involves working with a variety of types. Generics offer a way to create classes that can work with a variety of types while still retaining type safety.

Task: Implement a generic Queue class. The class should have methods: enqueue which adds an element to the end, and dequeue which removes an element from the front. The class should also have a size property.

Sample Code:

class Queue<T> {

    private storage: T[] = [];

    enqueue(item: T): void {

        this.storage.push(item);

    }


    dequeue(): T | undefined {

        return this.storage.shift();

    }

    get size(): number {

        return this.storage.length;

    }

}

let queue = new Queue<number>();

queue.enqueue(1);

queue.enqueue(2);

console.log(queue.size); // outputs 2

console.log(queue.dequeue()); // outputs 1

Explanation: This generic Queue class is built to handle elements of any type T. The enqueue method uses Array.prototype.push to add items at the end, while dequeue uses Array.prototype.shift to remove items from the front. The size getter property provides the current size of the queue.

6. Type Guards

As TypeScript is a statically typed superset of JavaScript, it allows for type checking at compile time. But, in many scenarios, we need to check types during runtime. This is where TypeScript’s type guards come in handy. They are a way to provide extra type information based on runtime values.

Task: Write a function isNumber that acts as a type guard for number.

Sample Code:

function isNumber(value: any): value is number {

    return typeof value === "number";

}

function process(value: number | string) {

    if (isNumber(value)) {

        return value.toFixed(2); // available because 'value' is guaranteed to be a number here

    } else {

        return value.trim();

    }

}

Explanation: The isNumber function is a user-defined type guard that checks if a value is a number. Inside process, we use this type guard to narrow the type of value from number | string to number within the if block. This allows us to use the toFixed method, which is only available on numbers.

7. Implement a Mixin

Mixins are a design concept in TypeScript that allows a developer to create reusable class factories. With mixins, we can create complex classes by combining simpler base classes. This question explores your knowledge of this advanced TypeScript concept.

Task: Implement a Disposable mixin. This should include a dispose method and an isDisposed property.

Sample Code:

class Disposable {

    isDisposed: boolean;

    dispose() {

        this.isDisposed = true;

    }

}


class SmartObject implements Disposable {

    constructor() {

        setInterval(() => console.log(this.isDisposed), 500);

    }


    interact() {

        this.dispose();

    }


    isDisposed: boolean = false;

    dispose: () => void;

}


applyMixins(SmartObject, [Disposable]);

let smartObj = new SmartObject();

setTimeout(() => smartObj.interact(), 1000);

function applyMixins(derivedCtor: any, baseCtors: any[]) {

    baseCtors.forEach(baseCtor => {

        Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {

            derivedCtor.prototype[name] = baseCtor.prototype[name];

        });

    });

}

Explanation: The applyMixins function copies the methods from the Disposable class into the SmartObject class at runtime, which allows SmartObject to access the isDisposed property and dispose method.

 

This article was written with the help of AI. Can you tell which parts?

The post 7 TypeScript Interview Questions Every Developer Should Know appeared first on HackerRank Blog.

]]>
https://www.hackerrank.com/blog/typescript-interview-questions-developers-should-know/feed/ 0