Interview Preparation Archives - HackerRank Blog https://bloghr.wpengine.com/blog/tag/interview-preparation/ 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 Interview Preparation Archives - HackerRank Blog https://bloghr.wpengine.com/blog/tag/interview-preparation/ 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
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
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
7 C++ Interview Questions Every Developer Should Know https://www.hackerrank.com/blog/c-plus-plus-interview-questions/ https://www.hackerrank.com/blog/c-plus-plus-interview-questions/#respond Wed, 14 Jun 2023 12:45:49 +0000 https://www.hackerrank.com/blog/?p=18804 In the 40 years since its introduction, C++ has carved out its place in the...

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

]]>
An AI-generated image of computer hardware in blue over a black background

In the 40 years since its introduction, C++ has carved out its place in the infrastructure of many of our favorite software, systems, and games. Its unique blend of high-level and low-level language features, object-oriented paradigm, and raw power gives it a level of flexibility and performance that’s hard to match. As a result, C++ continues to be one of the most sought-after programming languages, with tech professionals globally striving to master it.

In light of its significance, excelling in C++ technical interviews becomes paramount for aspiring and seasoned programmers alike. These interviews act as gateways to coveted roles in the tech industry, and a deep understanding of C++ concepts, coupled with a knack for problem solving, can be your ticket to success.

In this blog post, we’ll delve into some essential C++ interview questions that test both your foundational knowledge and your understanding of advanced C++ concepts. These handpicked questions aim to mirror the kind of challenges you might face in a real C++ technical interview, whether you’re seeking a role in systems programming, game development, or any tech domain that calls for C++ expertise. By the end of this guide, you should be better equipped to impress in your next C++ coding interview. 

Understanding the C++ Interview

Roles that call for C++ proficiency span a wide range, from system-level roles to game development and even financial technology roles. These roles can include software engineers, back-end developers, quality analysts, game programmers, embedded engineers, and programming architects.  As part of the interview process for these positions, candidates will likely face C++ interview questions designed to gauge their depth of understanding and practical expertise as it pertains to the role.

Now, let’s delve into some of these critical C++ interview questions, ranging from intermediate to advanced levels. Each question will also come with a sample answer to provide practical insight into how you could tackle such problems in a live interview setting.

1. Attribute Parser

This challenge works with a custom-designed markup language HRML. In HRML, each element consists of a starting and ending tag, and there are attributes associated with each tag. Only starting tags can have attributes. We can call an attribute by referencing the tag, followed by a tilde, ‘~’, and the name of the attribute. The tags may also be nested.

The opening tags follow the format:

<tag-name attribute1-name = "value1" attribute2-name = "value2" ...>

The closing tags follow the format:

</tag-name>

The attributes are referenced as:

tag1~value  

tag1.tag2~name

Given the source code in HRML format consisting of N lines, answer Q queries. For each query, print the value of the attribute specified. Print “Not Found!” if the attribute does not exist.

Example

HRML listing

<tag1 value = "value">

<tag2 name = "name">

<tag3 another="another" final="final">

</tag3>

</tag2>

</tag1>


Queries

tag1~value

tag1.tag2.tag3~name

tag1.tag2~value

Here, tag2 is nested within tag1, so attributes of tag2 are accessed as tag1.tag2~<attribute>. The results of the queries are:

Query                 Value

tag1~value            "value"

tag1.tag2.tag3~name   "Not Found!"

tag1.tag2.tag3~final  "final"

Input Format

The first line consists of two space-separated integers, N and Q. N specifies the number of lines in the HRML source program. Q specifies the number of queries.

The following N lines consist of either an opening tag with zero or more attributes or a closing tag. There is a space after the tag-name, attribute-name, ‘=’, and value. There is no space after the last value. If there are no attributes there is no space after the tag name.

Q queries follow. Each query consists of a string that references an attribute in the source program. More formally, each query is of the form tagᵢ1 . tagᵢ2 . tagᵢ3 …. tagᵢm ~attr – name where m>=1 and tagᵢ₁ . tagᵢ₂ …. tagᵢm are valid tags in the input.

Constraints

1 ≤ N ≤ 20

1 ≤ Q ≤ 20

  • Each line in the source program contains, at most, 200 characters.
  • Every reference to the attributes in the Q queries contains at most 200 characters.
  • All tag names are unique and the HRML source program is logically correct, i.e. valid nesting.
  • A tag may have no attributes.

Output Format

Print the value of the attribute for each query. Print “Not Found!” without quotes if the attribute does not exist.

Sample Input

4 3
<tag1 value = “HelloWorld”>
<tag2 name = “Name1”>
</tag2>
</tag1>
tag1.tag2~name
tag1~name
tag1~value

Sample Output

Name1
Not Found!
HelloWorld

Solve the problem.

2. Inherited Code

You inherited a piece of code that performs username validation for your company’s website. The existing function works reasonably well, but it throws an exception when the username is too short. Upon review, you realize that nobody ever defined the exception.

The inherited code is provided for you in the locked section of your editor. Complete the code so that, when an exception is thrown, it prints Too short: n (where n is the length of the given username).

Input Format

The first line contains an integer, t, the number of test cases.

Each of the t subsequent lines describes a test case as a single username string, u.

Constraints

  • 1 ≤ t ≤ 1000
  • 1 ≤ │u│≤ 100
  • The username consists only of uppercase and lowercase letters.

Output Format

You are not responsible for directly printing anything to stdout. If your code is correct, the locked stub code in your editor will print either Valid (if the username is valid), Invalid (if the username is invalid), or Too short: n (where n is the length of the too-short username) on a new line for each test case.

Sample Input

3

Peter

Me

Arxwwz

Sample Output

Valid
Too short: 2
Invalid

Explanation

Username Me is too short because it only contains 2 characters, so your exception prints Too short: 2.

All other validation is handled by the locked code in your editor.

Solve the problem.

3. Virtual Functions

This problem is to get you familiar with virtual functions. Create three classes: Person, Professor, and Student. The class Person should have data members name and age. The classes Professor and Student should inherit from the class Person.

The class Professor should have two integer members: publications and cur_id. There will be two member functions: getdata and putdata. The function getdata should get the input from the user: the name, age and publications of the professor. The function putdata should print the name, age, publications, and the cur_id of the professor.

The class Student should have two data members: marks, which is an array of size 6 and cur_id. It has two member functions: getdata and putdata. The function getdata should get the input from the user: the name, age, and the marks of the student in 6 subjects. The function putdata should print the name, age, sum of the marks, and the cur_id of the student.

For each object being created of the Professor or the Student class, sequential ID’s should be assigned to them starting from 1.

Solve this problem using virtual functions, constructors, and static variables. You can create more data members if you want.

Note: Expand the main function to look at how the input is being handled.

Input Format

The first line of input contains the number of objects that are being created. If the first line of input for each object is 1, it means that the object being created is of the Professor class. You will have to input the name, age, and publications of the professor.

If the first line of input for each object is 2, it means that the object is of the Student class. You will have to input the name, age, and the marks of the student in 6 subjects.

Constraints

1 ≤ lenname ≤ 100, where lenname is the length of the name.

1 ≤ age ≤  80

1 ≤ publications ≤ 100

0 ≤ marks ≤ ≤ 100, where marks is the marks of the student in each subject.

Output Format

There are two types of output depending on the object.

If the object is of type Professor, print the space-separated name, age, publications, and id on a new line.

If the object is of the Student class, print the space-separated name, age, the sum of the marks in 6 subjects, and id on a new line.

Sample Input

4
1
Walter 56 99
2
Jesse 18 50 48 97 76 34 98
2
Pinkman 22 10 12 0 18 45 50
1
White 58 87

Sample Output

Walter 56 99 1
Jesse 18 403 1
Pinkman 22 135 2
White 58 87 2

Solve the problem.

4. Operator Overloading

Classes define new types in C++. Types in C++ not only interact by means of constructions and assignments but also via operators. For example:

int a=2, b=1, c;

c = b + a;

The result of variable c will be 3.

Similarly, classes can also perform operations using operator overloading. Operators are overloaded by means of operator functions, which are regular functions with special names. Their name begins with the operator keyword followed by the operator sign that is overloaded. The syntax is: type operator sign (parameters) { /*… body …*/ }

You are given a main() function which takes a set of inputs to create two matrices and prints the result of their addition. You need to write the class Matrix, which has a member a of type vector<vector<int> >. You also need to write a member function to overload the operator +. The function’s job will be to add two objects of Matrix type and return the resultant Matrix.

Input Format

The first line will contain the number of test cases T. For each test case, there are three lines of input.

The first line of each test case will contain two integers N and M, which denote the number of rows and columns respectively of the two matrices that will follow on the next two lines. These next two lines will each contain N * M elements describing the two matrices in row-wise format, i.e. first M elements belong to the first row, next M elements belong to the second row, and so on.

Constraints

1<= T <= 1000

1 <= N <= 100

1 <= M <= 100

1 <= Ai,j <= 10, where Ai,j is the element in the ith row and jth column of the matrix.

Output Format

The code provided in the editor will use your class Matrix and overloaded operator function to add the two matrices and give the output.

Sample Input

1
2 2
2 2 2 2
1 2 3 4

Sample Output

3 4
5 6

Explanation

The sum of the first matrix and the second matrix is the matrix given in the output.

Solve the problem.

5. Abstract Classes – Polymorphism

Abstract base classes in C++ can only be used as base classes. Thus, they are allowed to have virtual member functions without definitions.

A cache is a component that stores data so future requests for that data can be served faster. The data stored in a cache might be the results of an earlier computation or the duplicates of data stored elsewhere. A cache hit occurs when the requested data can be found in a cache, while a cache miss occurs when it cannot. Cache hits are served by reading data from the cache, which is faster than recomputing a result or reading from a slower data store. Thus, the more requests that can be served from the cache, the faster the system performs.

One of the popular cache replacement policies is “least recently used” (LRU). It discards the least recently used items first.

For example, if a cache with a capacity to store 5 keys has the following state (arranged from most recently used key to least recently used key): 5 3 2 1 4

Now, if the next key comes as 1 (which is a cache hit), then the cache state in the same order will be: 1 5 3 2 4

Now, if the next key comes as 6 (which is a cache miss), then the cache state in the same order will be: 6 1 5 3 2

You can observe that 4 has been discarded because it was the least recently used key, and since the capacity of cache is 5, it could not be retained in the cache any longer.

Given an abstract base class Cache with member variables and functions:

  • mp – Map the key to the node in the linked list
  • cp – Capacity
  • tail – Double linked list tail pointer
  • head – Double linked list head pointer
  • set() – Set/insert the value of the key, if present, otherwise add the key as the most recently used key. If the cache has reached its capacity, it should replace the least recently used key with a new key.
  • get() – Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.

You have to write a class LRUCache, which extends the class Cache and uses the member functions and variables to implement an LRU cache.

Input Format

The first line of input will contain the N number of lines containing get or set commands followed by the capacity M of the cache.

The following N lines can either contain get or set commands.

An input line starting with get will be followed by a key to be found in the cache. An input line starting with set will be followed by the key and value respectively to be inserted/replaced in the cache.

Constraints

1<= N <= 500000

1 <= M <= 1000

1 <= key <= 20

1 <= value <= 2000

Output Format

The code provided in the editor will use your derived class LRUCache to output the value whenever a get command is encountered.

Sample Input

3 1
set 1 2
get 1
get 2
Sample Output

2
-1

Explanation

Since the capacity of the cache is 1, the first set results in setting up the key 1 with its value 2. The first get results in a cache hit of key 1, so 2 is printed as the value for the first get. The second get is a cache miss, so -1 is printed.

Solve the problem.

6. C++ Variadics

A template parameter pack is a template parameter that accepts zero or more template arguments (non-types, types, or templates). To read more about parameter packs, click here.

Create a template function named reversed_binary_value. It must take an arbitrary number of bool values as template parameters. These booleans represent binary digits in reverse order. Your function must return an integer corresponding to the binary value of the digits represented by the booleans. For example, reversed_binary_value<0,0,1>() should return 4.

Input Format

The first line contains an integer, t, the number of test cases. Each of the t subsequent lines contains a test case. A test case is described as 2 space-separated integers, x and y, respectively.

  • x is the value to compare against.
  • y represents the range to compare: 64 × y to 64 × y + 63.

Constraints

  • 0 ≤ x ≤ 65535
  • 0 ≤ y ≤ 1023
  • The number of template parameters passed to reversed_binary_value will be ≤ 16.

Output Format

Each line of output contains 64 binary characters (i.e., 0’s and 1’s). Each character represents one value in the range. The first character corresponds to the first value in the range. The last character corresponds to the last value in the range. The character is 1 if the value in the range matches x; otherwise, the character is 0.

Sample Input

2
65 1
10 0
Sample Output

0100000000000000000000000000000000000000000000000000000000000000
0000000000100000000000000000000000000000000000000000000000000000

Explanation

The second character on the first line is a 1, because the second value in the range 64..127 is 65 and x is 65.

The eleventh character on the second line is a 1, because the eleventh value in the range 0..63 is 10 and x is 10.

All other characters are zero because the corresponding values in the range do not match x.

Solve the problem.

7. Bit Array

You are given four integers: N, S, P, Q. You will use them in order to create the sequence a with the following pseudo-code:

a[0] = S (modulo 2^31)

for i = 1 to N-1

    a[i] = a[i-1]*P+Q (modulo 2^31) 

Your task is to calculate the number of distinct integers in the sequence a.

Input Format

Four space-separated integers on a single line, N, S, P, and Q respectively.

Output Format

A single integer that denotes the number of distinct integers in the sequence a.

Constraints

1 ≤ N ≤ 108

0 ≤ S, P, Q < 231

Sample Input

3 1 1 1
Sample Output

3

Explanation

a = [1,2,3]

Hence, there are 3 different integers in the sequence.

Solve the problem.

Resources to Improve C++ Knowledge

HackerRank C++ Practice Questions

HackerRank Interview

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/c-plus-plus-interview-questions/feed/ 0
7 JavaScript Interview Questions Every Developer Should Know https://www.hackerrank.com/blog/javascript-interview-questions-developers-should-know/ https://www.hackerrank.com/blog/javascript-interview-questions-developers-should-know/#respond Tue, 30 May 2023 12:45:38 +0000 https://www.hackerrank.com/blog/?p=18728 JavaScript has emerged as the cornerstone of modern web development, enabling dynamic and interactive experiences...

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

]]>
An AI-generated image with colorful shapes and connections

JavaScript has emerged as the cornerstone of modern web development, enabling dynamic and interactive experiences that shape the digital landscape. As a result of its widespread use, it also happens to be one of the world’s most ​​in-demand programming languages

As a JavaScript developer, excelling in technical interviews is paramount for showcasing your expertise and securing coveted positions in the industry, and a great way to prepare is to put your skills to the test.

In this blog post, we’ll explore seven intermediate-to-advanced JavaScript interview questions that will push the boundaries of your problem-solving skills, challenge your understanding of key concepts, and demonstrate your ability to navigate complex scenarios. Whether you are a seasoned JavaScript developer seeking to refresh your interview readiness or a hiring manager looking to identify top talent, this guide will equip you with invaluable insights and practical examples.

Inside a JavaScript Interview

JavaScript, often referred to as the “language of the web,” is a versatile programming language that plays a vital role in modern web development. It is primarily used to create interactive and dynamic elements on websites, enabling a rich user experience. 

When it comes to JavaScript interviews, they serve as a critical evaluation of a candidate’s JavaScript proficiency, problem-solving skills, and understanding of key concepts. A JavaScript interview can take various forms, depending on the company and position. However, it typically involves one or more of the following assessment formats:

  • Technical screenings
  • Coding challenges
  • Whiteboard exercises
  • Take-home assignments
  • Pair programming sessions
  • Behavioral interviews

These components are designed to assess different aspects of a candidate’s capabilities and provide a comprehensive evaluation of their JavaScript knowledge and expertise.

Roles that require candidates to complete a JavaScript interview span a wide range of technical positions. Web developers, back-end developers, front-end developers, and software engineers often encounter JavaScript interview questions as part of the hiring process. Additionally, positions in mobile app development, UI/UX design, and even emerging technologies like serverless computing may involve JavaScript assessments to gauge a candidate’s ability to work with its frameworks and libraries.

#1. Reverse Words in a Sentence

This question focuses on reversing the order of words in a given sentence, demonstrating a developer’s proficiency with string manipulation, loops, conditionals, and other programming constructs.

Task: Write a JavaScript function called reverseWords that takes a sentence as input and returns the sentence with the order of words reversed.

Input Format: The input will be a string representing the sentence.

Constraints:

  • The sentence will contain only alphanumeric characters and spaces.
  • There will be no leading or trailing spaces.
  • The sentence will have at least one word.

Output Format: The output will be a string representing the sentence with the words reversed.

Sample Input: JavaScript is awesome

Sample Output: awesome is JavaScript

Sample Code:

function reverseWords(sentence) {

    const words = sentence.split(” “);

    const reversedWords = words.reverse();

    const reversedSentence = reversedWords.join(” “);

    return reversedSentence;

}

Explanation:

  • The reverseWords function starts by splitting the sentence into individual words using the split(” “) method. This creates an array of words.
  • Next, the function uses the reverse() method to reverse the order of the words in the array.
  • The reversed words are then joined back together using the join(” “) method, where the space character ” “ is used as the separator.
  • Finally, the reversed sentence is returned.

#2. Find the Nth Largest Element in an Array

This question delves into array manipulation and algorithmic problem solving, showcasing a developer’s ability to work with arrays and efficiently find the nth largest element.

Task: Write a JavaScript function called findNthLargest that takes an array of numbers and an integer n as input, and returns the nth largest element from the array.

Input Format

  • The input will be an array of numbers.
  • An additional integer n will be provided.

Constraints

  • The array will contain at least n elements.
  • The array may have duplicates.
  • The values in the array can be both positive and negative.

Output Format: The output will be the nth largest element as a number.

Sample Input:

const numbers = [10, 5, 3, 8, 2];

const n = 3;

Sample Output: 5

Sample Code:

function findNthLargest(numbers, n) {

    numbers.sort((a, b) => b – a);

    return numbers[n – 1];

}

Explanation:

The findNthLargest function starts by sorting the numbers array in descending order using the sort() method with a custom comparison function (a, b) => b – a. This places the largest numbers at the beginning of the array.

Then, the function returns the element at index n – 1 since arrays are zero-indexed. In our example, we want to find the 3rd largest element, so we access numbers[2], which is 5.

#3. Implementing a Linked List

This question focuses on data structures and their implementation in JavaScript, specifically the Linked List. Demonstrating proficiency in data structures showcases a developer’s ability to design efficient and scalable solutions.

Task: Implement a Linked List in JavaScript with the following operations:

  • insert(value): Inserts a new node with the given value at the end of the list.
  • delete(value): Removes the first occurrence of the node with the given value from the list.
  • search(value): Returns true if a node with the given value exists in the list, false otherwise.

Sample Code:

class Node {

    constructor(value) {

        this.value = value;

        this.next = null;

    }

}

class LinkedList {

    constructor() {

        this.head = null;

    }

    insert(value) {

        const newNode = new Node(value);

 

        if (!this.head) {

            this.head = newNode;

        } else {

            let current = this.head;

            while (current.next) {

                current = current.next;

            }

            current.next = newNode;

        }

    }

    delete(value) {

        if (!this.head) {

            return;

        }

        if (this.head.value === value) {

            this.head = this.head.next;

            return;

        }

        let current = this.head;

        let previous = null;

        while (current && current.value !== value) {

            previous = current;

            current = current.next;

        }

        if (!current) {

            return;

        }

        previous.next = current.next;

    }

    search(value) {

        let current = this.head;

        while (current) {

            if (current.value === value) {

                return true;

            }

            current = current.next;

        }

        return false;

    }

}

// Usage example:

const linkedList = new LinkedList();

linkedList.insert(5);

linkedList.insert(10);

linkedList.insert(15);

linkedList.delete(10);

console.log(linkedList.search(5)); // Output: true

console.log(linkedList.search(10)); // Output: false

 

Explanation:

The code snippet above demonstrates the implementation of a Linked List in JavaScript. 

The Node class represents a single node in the Linked List, containing a value property to store the node’s value and a next property to reference the next node in the list.

The LinkedList class represents the Linked List itself. It has a head property that initially points to null. The insert method inserts a new node with the given value at the end of the list by traversing to the last node and appending the new node. The delete method removes the first occurrence of a node with the given value from the list by updating the next references of the surrounding nodes. The search method traverses the list to check if a node with the given value exists.

In the usage example, we create a new Linked List, insert nodes with values 5, 10, and 15, delete the node with value 10, and then perform search operations to check for the existence of nodes with values 5 and 10.

#4. Implementing a Class Hierarchy with Inheritance

This question delves into object-oriented programming (OOP) concepts in JavaScript, specifically class hierarchies and inheritance. Demonstrating proficiency in OOP showcases a developer’s ability to design modular and reusable code.

Task: Implement a class hierarchy in JavaScript with inheritance, following the given specifications:

  • Create a base class called Shape with the following properties and methods:
    • name: a string representing the name of the shape.
    • area(): a method that calculates and returns the area of the shape (to be implemented by subclasses).
  • Create a subclass called Rectangle that extends the Shape class. It should have the following additional properties and methods:
    • width: a number representing the width of the rectangle.
    • height: a number representing the height of the rectangle.
    • Implement the area() method to calculate and return the area of the rectangle.
  • Create another subclass called Circle that extends the Shape class. It should have the following additional properties and methods:
    • radius: a number representing the radius of the circle.
    • Implement the area() method to calculate and return the area of the circle.

Sample Code

class Shape {

    constructor(name) {

        this.name = name;

    }

    area() {

        // To be implemented by subclasses

    }

}

class Rectangle extends Shape {

    constructor(name, width, height) {

        super(name);

        this.width = width;

        this.height = height;

    }

    area() {

        return this.width * this.height;

    }

}

class Circle extends Shape {

    constructor(name, radius) {

        super(name);

        this.radius = radius;

    }

    area() {

        return Math.PI * Math.pow(this.radius, 2);

    }

}

// Usage example:

const rectangle = new Rectangle(“Rectangle”, 5, 3);

console.log(rectangle.area()); // Output: 15

const circle = new Circle(“Circle”, 4);

console.log(circle.area()); // Output: 50.26548245743669

Explanation:

The code snippet above demonstrates the implementation of a class hierarchy in JavaScript using inheritance.

The Shape class serves as the base class, providing a common name property for all shapes and a placeholder area() method that is meant to be implemented by subclasses.

The Rectangle class extends the Shape class using the extends keyword. It introduces additional properties width and height and overrides the area() method to calculate and return the area of a rectangle based on its width and height.

The Circle class also extends the Shape class and adds the radius property. The area() method is implemented to calculate and return the area of a circle based on its radius, using the formula π * r^2.

In the usage example, we create instances of the Rectangle and Circle classes, passing the necessary parameters. We then call the area() method on each instance to calculate and display the area of the respective shape.

#5. Finding the Longest Substring Without Repeating Characters

This question focuses on problem-solving skills and string manipulation. It challenges developers to find an efficient algorithm for finding the longest substring in a given string without repeating characters.

Task: Write a JavaScript function called findLongestSubstring that takes a string as input and returns the length of the longest substring without repeating characters.

Input Format: The input will be a string.

Constraints:

  • The string may contain uppercase and lowercase letters, digits, symbols, or spaces.
  • The string can have both single and multiple words.

Output Format: The output will be an integer representing the length of the longest substring without repeating characters.

Sample Input: abcabcbb

Sample Output: 3

Sample Code:

function findLongestSubstring(str) {

    let maxLength = 0;

    let start = 0;

    const charMap = {};

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

        const currentChar = str[i];

        if (charMap[currentChar] >= start) {

            start = charMap[currentChar] + 1;

        }

        charMap[currentChar] = i;

        maxLength = Math.max(maxLength, i – start + 1);

    }

    return maxLength;

Explanation:

The findLongestSubstring function utilizes the sliding window technique to efficiently find the length of the longest substring without repeating characters.

The function initializes maxLength to 0, start to 0, and an empty charMap object to keep track of the most recent occurrence of each character in the string.

The function then iterates through the string using a for loop. For each character, it checks if the character has been previously encountered within the current substring (i.e., its index is greater than or equal to start). If so, it updates the start index to the next position after the previous occurrence of the character.

The function updates the charMap with the current character’s index. It also calculates the length of the current substring by subtracting start from the current index and adding 1. The maximum length is updated using Math.max() to keep track of the longest substring found so far.

Finally, the function returns the maxLength, representing the length of the longest substring without repeating characters.

#6. Sum of Two Numbers in an Array

This question challenges your problem-solving skills and array manipulation techniques. It requires finding two numbers in an array that add up to a given target sum.

Task: Write a JavaScript function called findSumOfTwo that takes an array of numbers and a target sum as input and returns an array containing the two numbers that add up to the target sum. If no such pair is found, return an empty array.

Input Format: The input will be an array of numbers and a target sum.

Constraints:

  • The array may contain positive and negative integers.
  • The array may have duplicates.
  • The array can be empty.

Output Format: The output will be an array containing the two numbers that add up to the target sum, or an empty array if no such pair is found.

Sample Input:

const arr = [2, 4, 7, 11, 15];

const target = 9;

Sample Output: [2, 7]

Sample Code:

function findSumOfTwo(arr, target) {

    const numMap = {};

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

        const num = arr[i];

        const complement = target – num;

        if (numMap[complement] !== undefined) {

            return [complement, num];

        }

        numMap[num] = i;

    }

    return [];

}

Explanation:

The findSumOfTwo function utilizes a hash map to efficiently find the pair of numbers that add up to the target sum.

The function initializes an empty numMap object to store the numbers and their corresponding indices encountered during the iteration.

It then iterates through the array using a for loop. For each number num, it calculates the complement by subtracting num from the target

The function checks if the complement exists as a key in the numMap object. If it does, it means that a pair of numbers that adds up to the target sum has been found. The function returns an array containing the complement and num.

If no such pair is found during the iteration, the function returns an empty array [].

#7. Working with Asynchronous JavaScript and Callbacks

This question dives into asynchronous programming in JavaScript and challenges developers to work with callbacks to handle asynchronous operations.

Task: Write a JavaScript function called fetchData that simulates an asynchronous API call and takes a callback function as an argument. The callback function should be invoked with the retrieved data as its parameter.

Input Format: The input will be a callback function.

Output Format: The output will be the retrieved data passed to the callback function.

Sample Input:

function handleData(data) {

    console.log(“Received data:”, data);

}

fetchData(handleData);

Sample Output:

Received data: { name: ‘John’, age: 28, city: ‘New York’ }

Sample Code:

function fetchData(callback) {

    // Simulating an asynchronous API call with a setTimeout

    setTimeout(() => {

        const data = { name: ‘John’, age: 28, city: ‘New York’ };

        callback(data);

    }, 2000);

}

Explanation:

The fetchData function simulates an asynchronous API call using setTimeout. In this example, it waits for 2,000 milliseconds (2 seconds) before invoking the callback function with the retrieved data.

In the sample input, the handleData function is defined as the callback function. When fetchData is called, it waits for 2 seconds and then invokes the handleData function, passing the retrieved data as the parameter.

The handleData function in this case simply logs the received data to the console.

Resources to Improve JavaScript Knowledge

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

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

]]>
https://www.hackerrank.com/blog/javascript-interview-questions-developers-should-know/feed/ 0
8 Python Interview Questions Every Developer Should Know https://www.hackerrank.com/blog/python-interview-questions-developers-should-know/ https://www.hackerrank.com/blog/python-interview-questions-developers-should-know/#respond Thu, 25 May 2023 12:45:03 +0000 https://bloghr.wpengine.com/blog/?p=18719 Python has soared in popularity and cemented its position as one of the most widely...

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

]]>
Abstract, futuristic image of a computer generated by AI

Python has soared in popularity and cemented its position as one of the most widely used programming languages in the tech industry. Known for its elegant syntax, readability, and versatility, Python has gained a vast community of developers and has become a go-to language for a wide range of applications, from web development and data analysis to machine learning and artificial intelligence.

As Python continues to dominate the programming landscape, it has become increasingly crucial for both hiring managers and Python developers to have a solid understanding of essential Python interview questions. These questions serve as a litmus test for assessing a candidate’s proficiency in Python programming and their ability to apply Python’s features effectively. By delving into Python interview questions, hiring managers can identify top talent, while developers can refine their skills and confidently demonstrate their abilities during job interviews.

In this article, we’ll guide you through a carefully curated collection of Python interview questions, unravel their solutions, and provide clear explanations and illustrative code snippets to help you tackle Python interviews with confidence.

What a Python Interview Looks Like

Python is a high-level, object-oriented programming language that was first introduced in 1991 by Dutch programmer Guido van Rossum. The language is well known — and loved — for its robust set of tools and libraries, which make it suitable for a wide range of applications and use cases. In addition, Python’s clean syntax and extensive community support have made it a preferred choice for both beginners and experienced developers.

A Python interview serves as an opportunity for hiring managers to assess a candidate’s Python programming skills, problem-solving abilities, and familiarity with Python’s ecosystem. While the specific format and structure may vary depending on the company and position, Python interviews typically consist of several components aimed at evaluating different aspects of a candidate’s capabilities. These can include:

  • Technical screenings
  • Coding challenges
  • Whiteboarding exercises 
  • Take-home assignments
  • Pair programming sessions
  • Behavioral interviews

Given Python’s versatility as a programming language, Python interview questions can come up in the hiring process for a number of technical roles, including software engineers, data scientists, data analysts, and machine learning engineers — to name just a few.

#1. Reverse Words in a Sentence

This question focuses on reversing the order of words in a given sentence, demonstrating a developer’s proficiency with string manipulation, loops, conditionals, and other programming constructs.

Task: Write a Python function called reverse_words that takes a sentence as input and returns the sentence with the order of words reversed.

Input Format: The input will be a string representing the sentence.

Constraints

  • The sentence will contain only alphanumeric characters and spaces.
  • There will be no leading or trailing spaces.
  • The sentence will have at least one word.

Output Format: The output will be a string representing the sentence with the words reversed.

Sample Input: Python is awesome

Sample Output: awesome is Python

Sample Code

def reverse_words(sentence):

    words = sentence.split()

    reversed_sentence = ' '.join(reversed(words))

    return reversed_sentence

Explanation

  • The reverse_words function starts by splitting the sentence into individual words using the split() method. This creates a list of words.
  • Next, the function uses the reversed() function to reverse the order of the words in the list.
  • The reversed words are then joined back together using the ‘ ‘.join() method, where the space character ‘ ‘ is used as the separator.
  • Finally, the reversed sentence is returned.

#2. Maximum Subarray Sum

This question asks the developer to find the maximum sum of a subarray within a given array. Questions like this can be helpful for demonstrating a mastery of skills like analytical thinking optimization, algorithms, and array manipulation. 

Task: Write a Python function called max_subarray_sum that takes an array of integers as input and returns the maximum sum of any contiguous subarray within the array.

Input Format: The input will be a list of integers.

Constraints

  • The length of the array will be at least 1.
  • The array may contain both positive and negative integers.

Output Format: The output will be a single integer representing the maximum sum of a subarray.

Sample Input: [1, 2, 3, -2, 5]

Sample Output: 9

Sample Code

def max_subarray_sum(arr):     
max_sum = arr[0]     
current_sum = arr[0]     
for i in range(1, len(arr)):         
current_sum = max(arr[i], current_sum + arr[i])         
max_sum = max(max_sum, current_sum)     
return max_sum

Explanation

  • The max_subarray_sum function utilizes Kadane’s algorithm to find the maximum sum of a subarray.
  • It starts by initializing max_sum and current_sum to the first element of the array.
  • Then, it iterates through the array, updating current_sum by either including the current element or starting a new subarray from the current element.
  • At each iteration, max_sum is updated to store the maximum sum encountered so far.
  • Finally, the function returns max_sum, which represents the maximum sum of any contiguous subarray within the given array.

#3. Merge Intervals

This question focuses on merging overlapping intervals within a given list, which gives recruiters insight into a developer’s ability to break down a complex problem, identify patterns, and design effective solutions, leveraging programming constructs like loops, conditionals, and list manipulation operations. 

Task: Write a Python function called merge_intervals that takes a list of intervals as input and returns a new list of intervals where overlapping intervals are merged.

Input Format: The input will be a list of intervals, where each interval is represented by a list with two elements: the start and end points of the interval.

Constraints

  • The list of intervals will be non-empty.
  • The start and end points of each interval will be integers.

Output Format: The output will be a list of merged intervals, where each interval is represented by a list with two elements: the start and end points of the merged interval.

Sample Input: [[1, 3], [2, 6], [8, 10], [15, 18]]

Sample Output: [[1, 6], [8, 10], [15, 18]]

Sample Code

def merge_intervals(intervals):     
intervals.sort(key=lambda x: x[0])     
merged = []     
for interval in intervals:         
if not merged or merged[-1][1] < interval[0]:             
merged.append(interval)         
else:             
merged[-1][1] = max(merged[-1][1], interval[1])     
return merged

Explanation

  • The merge_intervals function sorts the intervals based on their start points.
  • It initializes an empty list called merged to store the merged intervals.
  • Then, it iterates through each interval in the sorted list.
  • If the merged list is empty or the current interval does not overlap with the last merged interval, the current interval is appended to merged.
  • If the current interval overlaps with the last merged interval, the end point of the last merged interval is updated to the maximum of the two end points.
  • Finally, the function returns the `merged` list, which contains the merged intervals with no overlaps.

#4. Iterables and Iterators

Solve the Problem

The itertools module standardizes a core set of fast, memory efficient tools that are useful by themselves or in combination. Together, they form an iterator algebra making it possible to construct specialized tools succinctly and efficiently in pure Python.

To read more about the functions in this module, check out their documentation here.

You are given a list of N lowercase English letters. For a given integer K, you can select any K indices (assume 1-based indexing) with a uniform probability from the list.

Find the probability that at least one of the K indices selected will contain the letter: ‘a’.

Input Format: The input consists of three lines. The first line contains the integer N, denoting the length of the list. The next line consists of N space-separated lowercase English letters, denoting the elements of the list. The third and the last line of input contains the integer K, denoting the number of indices to be selected.

Output Format: Output a single line consisting of the probability that at least one of the K indices selected contains the letter: ‘a’.

Note: The answer must be correct up to 3 decimal places.

Constraints

  • 1 ≤ N ≤ 10
  • 1 ≤ K N

All the letters in the list are lowercase English letters.

Sample Input

a a c d

2

Sample Output: 0.8333

Explanation

All possible unordered tuples of length 2 comprising of indices from 1 to 4 are:

(1, 2) (1, 3) (1, 4) (2, 3) (2, 4) (3, 4)

Out of these 6 combinations, 5 of them contain either index 1 or index 2, which are the indices that contain the letter ‘a’.

Hence, the answer is ⅚.

#5. Time Delta

Solve the Problem

When users post an update on social media, such as a URL, image, status update, etc., other users in their network are able to view this new post on their news feed. Users can also see exactly when the post was published — i.e, how many hours, minutes, or seconds ago.

Since sometimes posts are published and viewed in different time zones, this can be confusing. You are given two timestamps of one such post that a user can see on his newsfeed in the following format:

Day dd Mon yyyy hh:mm:ss +xxxx

Here +xxxx represents the time zone. Your task is to print the absolute difference (in seconds) between them.

Input Format: The first line contains T, the number of test cases. Each test case contains 2 lines, representing time t₁ and time t₂.

Constraints

Input contains only valid timestamps.

year ≤ 3000

Output Format: Print the absolute difference (t₁ – t₂) in seconds.

Sample Input

2

Sun 10 May 2015 13:54:36 -0700

Sun 10 May 2015 13:54:36 -0000

Sat 02 May 2015 19:54:36 +0530

Fri 01 May 2015 13:54:36 -0000

Sample Output

25200

88200

Explanation: In the first query, when we compare the time in UTC for both the time stamps, we see a difference of 7 hours, which is 7 x 3,600 seconds or 25,200 seconds.

Similarly, in the second query, the time difference is 5 hours and 30 minutes for time zone. Adjusting for that, we have a difference of 1 day and 30 minutes. Or 24 x 3600 + 30 x 60 ⇒ 88200.

#6. start() & end()

Solve the Problem

These expressions return the indices of the start and end of the substring matched by the group.

Code
>>> import re

>>> m = re.search(r’\d+’,’1234′)

>>> m.end()

4

>>> m.start()

0

Task: You are given a string S. Find the indices of the start and end of string k in S.

Input Format: The first line contains the string S. The second line contains the string k.

Constraints

0 < len(S) < 100

0 < len(k) < len(S)

Output Format: Print the tuple in this format: (start _index, end _index). If no match is found, print (-1, -1).

Sample Input

aaadaa

aa
Sample Output

(0, 1)  

(1, 2)

(4, 5)

#7. Decorators 2 – Name Directory

Solve the Problem

Let’s use decorators to build a name directory. You are given some information about N people. Each person has a first name, last name, age, and sex. Print their names in a specific format sorted by their age in ascending order, i.e. the youngest person’s name should be printed first. For two people of the same age, print them in the order of their input.

For Henry Davids, the output should be:

Mr. Henry Davids

For Mary George, the output should be:

Ms. Mary George

Input Format: The first line contains the integer N, the number of people. N lines follow each containing the space separated values of the first name, last name, age, and sex, respectively.

Constraints: 1 ≤ N ≤ 10

Output Format: Output N names on separate lines in the format described above in ascending order of age.

Sample Input

3

Mike Thomson 20 M

Robert Bustle 32 M

Andria Bustle 30 F

Sample Output

Mr. Mike Thomson

Ms. Andria Bustle

Mr. Robert Bustle

Concept: For sorting a nested list based on some parameter, you can use the itemgetter library. You can read more about it here.

#8. Default Arguments

Solve the Problem

In this challenge, the task is to debug the existing code to successfully execute all provided test files. Python supports a useful concept of default argument values. For each keyword argument of a function, we can assign a default value which is going to be used as the value of said argument if the function is called without it. For example, consider the following increment function:

def increment_by(n, increment=1):

    return n + increment

The functions works like this:

>>> increment_by(5, 2)

7

>>> increment_by(4)

5

>>>

Debug the given function print_from_stream using the default value of one of its arguments.

The function has the following signature:

def print_from_stream(n, stream)

This function should print the first n values returned by get_next() method of stream object provided as an argument. Each of these values should be printed in a separate line.

Whenever the function is called without the stream argument, it should use an instance of EvenStream class defined in the code stubs below as the value of stream.

Your function will be tested on several cases by the locked template code.

Input Format: The input is read by the provided locked code template. In the first line, there is a single integer q denoting the number of queries. Each of the following q lines contains a stream_name followed by integer n, and it corresponds to a single test for your function.

Constraints

  • 1 ≤ q  ≤ 100
  • 1  ≤ n ≤ 10

Output Format: The output is produced by the provided and locked code template. For each of the queries (stream_name, n), if the stream_name is even then print_from_stream(n) is called. Otherwise, if the stream_name is odd, then print_from_stream(n, OddStream()) is called.

Sample Input 

3

odd 2

even 3

odd 5

Sample Output 

1

3

0

2

4

1

3

5

7

9

Explanation: There are 3 queries in the sample. 

In the first query, the function print_from_stream(2, OddStream()) is executed, which leads to printing values 1 and 3 in separated lines as the first two non-negative odd numbers.

In the second query, the function print_from_stream(3) is executed, which leads to printing values 2, 4 and 6 in separated lines as the first three non-negative even numbers.

In the third query, the function print_from_stream(5, OddStream()) is executed, which leads to printing values 1, 3, 5, 7 and 9 in separated lines as the first five non-negative odd numbers.

Resources to Improve Python Knowledge

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

]]>
https://www.hackerrank.com/blog/python-interview-questions-developers-should-know/feed/ 0