Codemonk

  • Basics of Input/Output
  • Time and Space Complexity
  • Basics of Implementation
  • Basics of Operators
  • Basics of Bit Manipulation
  • Recursion and Backtracking
  • Multi-dimensional
  • Basics of Stacks
  • Basics of Queues
  • Basics of Hash Tables
  • Singly Linked List
  • Binary/ N-ary Trees
  • Binary Search Tree
  • Heaps/Priority Queues
  • Trie (Keyword Tree)
  • Segment Trees
  • Fenwick (Binary Indexed) Trees
  • Suffix Trees
  • Suffix Arrays
  • Basics of Disjoint Data Structures
  • Linear Search
  • Binary Search
  • Ternary Search
  • Bubble Sort
  • Selection Sort
  • Insertion Sort
  • Counting Sort
  • Bucket Sort
  • Basics of Greedy Algorithms
  • Graph Representation
  • Breadth First Search
  • Depth First Search
  • Minimum Spanning Tree
  • Shortest Path Algorithms
  • Flood-fill Algorithm
  • Articulation Points and Bridges
  • Biconnected Components
  • Strongly Connected Components
  • Topological Sort
  • Hamiltonian Path
  • Maximum flow
  • Minimum Cost Maximum Flow
  • Basics of String Manipulation
  • String Searching
  • Z Algorithm
  • Manachar’s Algorithm
  • Introduction to Dynamic Programming 1
  • 2 Dimensional
  • State space reduction
  • Dynamic Programming and Bit Masking
  • Basic Number Theory-1
  • Basic Number Theory-2
  • Primality Tests
  • Totient Function
  • Basics of Combinatorics
  • Inclusion-Exclusion
  • Line Sweep Technique
  • Line Intersection using Bentley Ottmann Algorithm
  • Basic Probability Models and Rules
  • Bayes’ rules, Conditional probability, Chain rule
  • Discrete Random Variables
  • Continuous Random Variables
  • Practical Tutorial on Data Manipulation with Numpy and Pandas in Python
  • Beginners Guide to Regression Analysis and Plot Interpretations
  • Practical Guide to Logistic Regression Analysis in R
  • Practical Tutorial on Random Forest and Parameter Tuning in R
  • Practical Guide to Clustering Algorithms & Evaluation in R
  • Beginners Tutorial on XGBoost and Parameter Tuning in R
  • Deep Learning & Parameter Tuning with MXnet, H2o Package in R
  • Decision Tree
  • Simple Tutorial on Regular Expressions and String Manipulations in R
  • Practical Guide to Text Mining and Feature Engineering in R
  • Winning Tips on Machine Learning Competitions by Kazanova, Current Kaggle #3
  • Practical Machine Learning Project in Python on House Prices Data
  • Challenge #1 - Machine Learning
  • Challenge #3 - Machine Learning
  • Challenge #2 - Deep Learning
  • Transfer Learning Introduction
  • Input and Output
  • Python Variables
  • Conditionals
  • Expressions
  • Classes and Objects I
  • Classes and Objects II (Inheritance and Composition)
  • Errors and Exceptions
  • Iterators and Generators
  • Functional Programming
  • Higher Order Functions and Decorators
  • +1-650-461-4192
  • For sales enquiry [email protected]
  • For support [email protected]
  • Campus Ambassadors
  • Assessments
  • Learning and Development
  • Interview Prep
  • Engineering Blog
  • Privacy Policy
  • © 2024 HackerEarth All rights reserved
  • Terms of Service

code-practice

20 Code Challenges To Put What You’re Learning to the Test

Stephan-Miller.jpg?w=648

  • Share article on Twitter
  • Share article on Facebook
  • Share article on LinkedIn

Code challenges help you build problem-solving skills, better understand the programming language you use, and get to know algorithms you may not be familiar with. If you want to improve your skills in programming, there’s no better way than by writing code. In addition, coding challenges are convenient because they allow you to exercise your skills on a bite-sized problem and rarely require you to build a complete application, so you can usually complete them rather quickly.

Code challenges are also part of most coding interviews. Hiring managers may see the skills listed on your resume, and you may be able to talk like a programmer, but they also want to know that you can write code. By having you solve a coding challenge, they can assess your skills and be sure you can do the job. So working on coding challenges will also help you prepare for job interviews. We’ve collected 20 popular code challenges to get you started.

Learn something new for free

Intro to chatgpt, general programming challenges.

While most code challenges are small in scope, that doesn’t mean they won’t involve a complex solution, so it is best to choose a challenge that stretches your skills but isn’t completely out of your league. Below, we’ve ranked a few coding challenges by their complexity so you can find the best challenge for your skill level.

Basic code challenges

These are good beginner challenges. They may not actually show up in a coding interview, but everyone has to start somewhere. These challenges are good for practicing your skills at using a programming language.

  • Build a binary search tree .
  • Write a program that prints the numbers from 1 to 100. But for multiples of three, print Fizz instead of the number, and multiples of five, print Buzz. For numbers that are multiples of both three and five, print FizzBuzz .
  • Print Hello World in several different ways in a programming language .
  • Code in a new language .
  • Write a function that will take a given string and reverse the order of the words .
  • Write a function that will find the 50th number in the Fibonacci Sequence .
  • Write a function that tests if a number, n, is a prime number .

Intermediate code challenges

These code challenges are examples of what might be asked in interviews. There may be a big difference in difficulty compared to the basic challenges. If you get stuck on these, go back to the basics, practice more, and you will get there.

  • Write a function to check that a binary search tree is balanced .
  • Write a function to reverse the order of words that have punctuation and keep the punctuation in place .
  • Given two words (beginWord and endWord) and a dictionary’s word list, find the length of the shortest transformation sequence from beginWord to endWord .
  • Write a function that will find the nth number in the Fibonacci Sequence .
  • Write a function that will print out all prime numbers in a given string .

Hard code challenges

The point of these challenges is to challenge you, which will help you learn more. These will be similar to the type of work you’ll do on the job. Most of these challenges will be hard but use Big O notation and expect a certain type of performance. If you are struggling with these, search StackOverflow or Google for direction. Many developers have run into these types of problems and will help you find the solution. Just don’t cheat and copy the answer. What good would that do?

  • Write a function that inserts a list of n numbers into a binary search tree that runs at O(n log n) time .
  • Write a function to reverse the order of words with punctuation and keep the punctuation in place that runs at 0(n) time .
  • Write a function that will find the nth number in the Fibonacci Sequence and runs at O(n) time .
  • Write a function that tests if a number, n, is a prime number and a function that will print out all prime numbers in a given string as efficiently as possible .

Technology specific challenges

If you want to try some coding challenges that will test your skills on specific technologies, we have a few of those challenges.

Web development code challenges

  • Build a web page for your favorite band . A fun challenge can be creating a webpage for your favorite musical artist. Start by using only static HTML , and if you want to challenge yourself, even more, add CSS and JavaScript . Then, for extra credit, build it in a front-end framework like React and make it an interactive experience.
  • Recreate a magazine layout using Semantic HTML and CSS Flexbox . It is not always that easy to recreate a design. This code challenge will really test your skills with HTML and CSS by having you recreate a design from scratch on your own. Once you are a working web developer, you will be doing this daily.
  • Build a static portfolio site . Once you finish the first two web development challenges listed here, you will have demonstrated your skills in web development. So why not take it a step further and show off those skills to the world or a potential employer by building a portfolio site? With this challenge, you will do just that. You can use HTML and CSS and, if you want, JavaScript. If you need help creating a portfolio, watch the video below for a step-by-step tutorial. And if you want to learn how to use JavaScript to make it interactive, check out Part 2 .

Financial data analysis code challenges

Maximize stock trading profit . This is reportedly a question asked in a Google interview and will test your skills in analyzing financial data . There are three levels to this challenge:

  • Basic: Given the daily values of a stock, write a program that will find how you can gain the most with a single buy-sell-trade.
  • Intermediate: Given the daily values of a stock over several days n , write a program that will find how you can gain the most with a combination of buy-sell trades.
  • Hard: Complete both the basic and intermediate algorithms in the most efficient way possible.

Code challenges are a great way to practice your coding skills or keep yourself from getting rusty. Building complete applications will also teach you a lot, but they can take time to finish. On the other hand, a coding challenge can be completed in an evening and will expose you to new algorithms and programming concepts. They are also part of many coding interviews, so completing a few can help you prepare for a job interview. For more details on the code challenges we have, check out Essential Information on Code Challenges .

Whether you’re looking to break into a new career, build your technical skills, or just code for fun, we’re here to help every step of the way. Check out our blog post about how to choose the best Codecademy plan for you to learn about our structured courses, professional certifications, interview prep resources, career services, and more.

Related courses

Learn to code with blockly, choosing a programming language, choosing a career in tech, subscribe for news, tips, and more, related articles.

Header-Image_2083x875-12.png?w=1024

What is the Waterfall Model?

T​​he waterfall model follows a linear sequential flow where each phase of development is completed and approved before the next begins. Here’s how it works.

what-is-html.png?w=1024

What is HTML? Common Uses & Defining Features

HTML lies at the heart of web development and forms the structure of our favorite websites.

Pride-Day_R1_Blog2.webp?w=1024

10 Python Code Challenges to Try During Pride

Celebrate Pride with these bite-sized Python coding challenges.

7-Organizations-Helping-Girls---Women-Build-Careers-in-Tech-1.jpg?w=1024

8 Organizations Helping Girls & Women Build Careers in Tech

There’s a gender gap in tech — but it’s getting smaller thanks to organizations like these.

staying-accountable-coding-goals.png?w=1024

5 Ways to Stay Accountable to Your Learning Goals in 2024

Planning to learn to code in 2024? We’ve put together a list of 6 tips and resources to help you stay accountable to your coding goals this year.

goals-for-learning-to-code.png?w=1024

30 Bite-Sized Goals for Learning to Code in 2024

It’s that time of year again — the time for making New Year’s resolutions! This year, let’s resolve to make resolutions we can keep.

Highest-paying-jobs-that-dont-require-degrees-.webp?w=1024

6 High-Paying Jobs You Can Get Without a Degree

Learn about some of the high-paying jobs you can get without needing a degree. Discover what each job entails and how you can succeed with our classes.

PW Skills | Blog

75 Basic Programming Problems and Tutorials for Practice

' src=

Varun Saharawat is a seasoned professional in the fields of SEO and content writing. With a profound knowledge of the intricate aspects of these disciplines, Varun has established himself as a valuable asset in the world of digital marketing and online content creation.

Solving Basic Programming Problems is the key to achieve success in coding challenges. Students must practice these basic programming problems!

basic programming problems

Basic Programming Problems: Engaging in code challenges offers many benefits, serving as a dynamic tool to enhance problem-solving proficiency, deepen your comprehension of the programming language you work with, and acquaint yourself with diverse algorithms. If you aspire to elevate your programming skills, immersing yourself in coding is the most effective avenue.

The beauty of basic programming problems lies in their convenience—they provide a platform to hone your abilities through bite-sized problems, often eliminating the need to construct entire applications. This characteristic allows you to conquer these challenges swiftly, fostering a sense of accomplishment.

Moreover, code challenges are integral components of many coding interviews.

While your resume may showcase your skills and ability to articulate programming concepts, employers want to validate your practical coding capabilities. Tackling coding challenges during interviews becomes a testament to your proficiency and showcases your competence for the role.

Therefore, incorporating coding challenges into your routine sharpens your skills and is an invaluable preparation strategy for job interviews. To kickstart your coding journey, we have curated a collection of popular basic programming problems to pave the way for your continued growth.

Table of Contents

Recommended Technical Course

  • Full Stack Development Course
  • Generative AI Course
  • DSA C++ Course
  • Data Analytics Course
  • Python DSA Course
  • DSA Java Course

Basic Programming Problems Overview

Basic programming problems provide an essential foundation for individuals learning to code, offering a practical and hands-on approach to mastering fundamental concepts in programming.

These problems are designed to introduce beginners to the core coding principles, gradually building their problem-solving skills and comprehension of programming logic.

Whether you are a novice looking to embark on your coding journey or an experienced programmer aiming to reinforce your foundational knowledge, engaging with basic programming problems is a valuable practice.

These problems typically cover essential topics such as data types, loops, conditionals, functions, and basic algorithms, providing a well-rounded introduction to the key building blocks of programming.

The significance of basic programming problems extends beyond mere skill development; it serves as a stepping stone for individuals aspiring to pursue more advanced coding challenges and projects.

By grappling with these foundational problems, learners can cultivate a solid understanding of programming fundamentals, laying the groundwork for future exploration and mastery of more complex coding concepts. Basic programming problems are the cornerstone of a programmer’s educational journey, fostering a strong and resilient coding skill set.

Basic Programming Problems for Beginners

Starting your career in the programming field is  exciting and challenging. For beginners, mastering the basics is crucial, and what better way to do so than by solving basic programming problems ?

1 Hello World: Print “Hello, World!” to the console.
2 Sum of Two Numbers: Add two numbers and print the result.
3 Factorial of a Number: Calculate the factorial of a number.
4 Check Even or Odd: Determine if a number is even or odd.
5 Reverse a String: Reverse the characters in a given string.
6 Fibonacci Series: Generate the Fibonacci series.
7 Check Prime Number: Check if a number is prime.
8 Find Maximum Element: Find the maximum element in an array.
9 Palindrome Check: Check if a string is a palindrome.
10 Simple Calculator: Implement a basic calculator.
11 Find Minimum Element: Find the minimum element in an array.

Basic Programming Problems Java

Here are some of the basic programming problems JAVA :

1) Hello World:

public class HelloWorld {

    public static void main(String[] args) {

        System.out.println(“Hello, World!”);

2) The sum of Two Numbers:

Add two numbers and print the result.

public class Sum {

        int num1 = 5, num2 = 10, sum;

        sum = num1 + num2;

        System.out.println(“Sum: ” + sum);

3) Factorial of a Number:

Calculate the factorial of a number.

public class Factorial {

        int num = 5;

        long factorial = 1;

        for (int i = 1; i <= num; ++i) {

            factorial *= i;

        System.out.println(“Factorial: ” + factorial);

4) Check Even or Odd:

Determine if a number is even or odd.

public class EvenOdd {

        int num = 8;

        if (num % 2 == 0) {

            System.out.println(num + ” is even.”);

        } else {

            System.out.println(num + ” is odd.”);

5) Reverse a String:

Reverse the characters in a given string.

public class ReverseString {

        String str = “Hello”;

        StringBuilder reversed = new StringBuilder(str).reverse();

        System.out.println(“Reversed String: ” + reversed);

Here are some theory-based basic programming problems Java:

1) Differences Between C++ and Java

  • C++: Not platform-independent, follows “write once, compile anywhere.”
  • Java: Platform-independent byte code allows programs to run on any machine.

Languages Compatibility:

  • C++: Compatible with most high-level languages.
  • Java: Incompatible with most languages, comparable to C and C++.

Interaction with the Library:

  • C++: Direct access to native system libraries, suitable for system-level programming.
  • Java: Requires Java Native Interface or library access, not direct call support.

Characteristics:

  • C++: Combines features of procedural and object-oriented languages.
  • Java: Known for automatic garbage collection, lacks support for destructors.

Semantics of the Type:

  • C++: Consistent semantics for primitive and object types.
  • Java: Inconsistent semantics between primitive and object types and classes.

Compiler and Interpreter:

  • Java: Compiled and interpreted language, source code compiles into platform-independent bytecode.
  • C++: Purely compiled language, source program compiles into object code, further executed.

2) Features of the Java Programming Language:

  • Easy: Java is considered easy to learn, with fundamental Object-Oriented Programming (OOP) concepts.
  • Secured Feature: Java provides a secured feature, ensuring the development of virus-free and tamper-free systems.
  • OOP: Java follows Object-Oriented Programming, treating everything as an object.
  • Independent Platform: Java compiles into platform-independent bytecode, interpreted by the Virtual Machine.

3) ClassLoader in Java:

  • A ClassLoader in Java is a subsystem of the Java Virtual Machine responsible for loading class files during program execution.
  • It is the first to load the executable file and includes Bootstrap, Extension, and Application classloaders.

4) Differences Between Heap and Stack Memory in Java:

  • Stack Memory: Allocated to each individual program. Fixed memory space.
  • Heap Memory: Not assigned to Java code initially but available during runtime. Used as needed by the Java code.

Embark on a transformative journey with our comprehensive course, “ Decode Java+DSA 1.0 ,” meticulously designed to empower you with the skills needed to excel in programming. This course seamlessly integrates Core Java and Data Structures and Algorithms (DSA), offering a holistic learning experience that lays a robust foundation for your programming journey.

Key Features:

  • Comprehensive Java Coverage: Delve into the intricacies of Core Java, unraveling the language’s syntax, features, and object-oriented programming concepts. From basic constructs to advanced topics, this course ensures a thorough understanding of Java.
  • Powerful Problem-Solving with DSA: Unlock the potential of Data Structures and Algorithms to efficiently solve complex problems. Acquire the essential tools and strategies to approach real-world challenges with confidence and precision.
  • Hands-On Learning: Immerse yourself in practical, hands-on exercises that reinforce theoretical concepts. Through coding exercises and projects, you’ll apply your knowledge, fostering a deeper understanding of both Java and DSA.
  • Expert Guidance: Benefit from expert guidance provided by seasoned instructors with extensive industry experience. Learn industry best practices and gain insights into the practical applications of Java and DSA.

Who Should Enroll:

  • Programming Enthusiasts
  • Students Pursuing Computer Science or Related Fields
  • Professionals Seeking to Strengthen Core Java and DSA Skills

Upon completion of “ Decode Java+DSA 1.0 ,” by PW you’ll emerge as a proficient programmer equipped with the skills to tackle diverse programming challenges. Whether you’re aiming to kickstart your programming career, enhance your academic pursuits, or upskill for professional growth, this course is your gateway to mastering Java and DSA. Elevate your programming prowess and embark on a journey of continuous learning and innovation.

Basic Programming Problems in C

The table below shows the basic programming problems in C :

1.

Hello World

Print “Hello, World!” to the console. Output: Hello, World!
2.

Sum of Two Numbers

Take two numbers and print their sum. Input: 5, 7; Output: 12
3.

Factorial Calculation

Calculate and print the factorial of a number. Input: 5; Output: 120
4.

Check Even or Odd

Determine if a number is even or odd. Input: 8; Output: Even
5.

Swap Two Numbers

Take two numbers and swap their values. Input: 3, 7; Output: 7, 3
6.

Prime Number Check

Check if a number is prime or not. Input: 11; Output: Prime
7.

Reverse a Number

Reverse the digits of a number. Input: 123; Output: 321
8.

Palindrome Check

Check if a number is a palindrome. Input: 121; Output: Palindrome
9.

Fibonacci Series

Print Fibonacci series. Input: 5; Output: 0, 1, 1, 2, 3
10.

Leap Year Check

Check if a year is a leap year. Input: 2020; Output: Leap Year

Put your learning into action with hands-on projects that simulate real-world scenarios with Decode Full Stack Web Dev 1.0 by PW . From designing responsive user interfaces to implementing robust server-side functionalities, you’ll gain practical experience that enhances your proficiency.

Learn essential tools like Git for version control, ensuring collaborative and efficient development. Explore deployment strategies to showcase your applications to the world, covering platforms like Heroku.

Who Should Enroll

  • Aspiring Web Developers 
  • Computer Science Students 
  • Professionals Transitioning to Web Development 
  • Entrepreneurs Looking to Build Web Applications

Basic Programming Problems in Python

In addition to introducing you to Python’s syntax and structure, tackling basic programming problems in Python helps you improve your problem-solving skills. With tasks ranging from basic logic puzzles to intricate algorithmic difficulties, these issues offer an interactive method of learning Python and put you on the route to becoming a skilled programmer.

Hello World Write a program that prints “Hello, World!” to the console.
Variables and Data Types Create variables of different data types (integers, floats, strings) and perform basic operations on them.
Conditional Statements Use if, elif, and else statements to implement basic conditional logic.
Loops Implement loops (for, while) to iterate through lists, perform a certain action, or solve iterative problems.
Lists and Arrays Manipulate lists and arrays: create, access, modify, and traverse elements.
Functions Define and call functions with parameters and return values.
File Handling Read from and write to files, handle exceptions for file operations.
Exception Handling Use try, except, finally blocks to handle exceptions and errors gracefully.
Basic Algorithms Implement basic algorithms such as sorting (e.g., bubble sort) searching (e.g., linear search)
Recursion Solve problems using recursive functions.
Object-Oriented Programming (OOP) Create classes, objects, and methods; implement inheritance and encapsulation.
Regular Expressions Use regular expressions for pattern matching and text manipulation.
List Comprehensions Write concise and expressive code using list comprehensions.
Lambda Functions Define anonymous functions using lambda expressions.
Error Handling and Logging Handle errors effectively and implement logging for debugging.
Basic Input/Output Take user input and display output using input() and print().
Virtual Environment and Packages Create virtual environments and install external packages using pip.

Basic Programming Problems in Javascript

Whether you aim to enhance your web development skills or explore the vast world of JavaScript applications, these problems cater to beginners, guiding them through the foundational aspects of programming in this versatile language. Below table showcases the basic programming problems in Javascript :

Hello World Write a program that prints “Hello, World!” to the console.
Variables and Data Types Create variables of different data types (numbers, strings, booleans) and perform basic operations on them.
Conditional Statements Use if, else if, and else statements to implement basic conditional logic.
Loops Implement loops (for, while) to iterate through arrays, perform a certain action, or solve iterative problems.
Arrays Manipulate arrays: create, access, modify, and iterate through elements.
Functions Define and call functions with parameters and return values.
Error Handling Use try, catch, and finally blocks to handle exceptions and errors gracefully.
Callbacks and Asynchronous Programming Understand and implement callbacks, handle asynchronous operations using callbacks.
Promises Use promises to handle asynchronous operations and manage asynchronous code more effectively.
JSON Parse and stringify JSON data.
DOM Manipulation Interact with the Document Object Model (DOM) to dynamically update HTML and respond to user events.
Event Handling Handle browser events such as click, submit, etc., using event listeners.
AJAX and Fetch API Make asynchronous HTTP requests using the Fetch API or XMLHttpRequest.
Local Storage and Cookies Store and retrieve data locally using local storage and cookies.
Basic Algorithms Implement basic algorithms such as sorting (e.g., bubble sort) and searching (e.g., linear search).
Recursion Solve problems using recursive functions.
Object-Oriented Programming (OOP) Create objects, classes, and methods; implement inheritance and encapsulation.
ES6 Features Use ES6 features such as arrow functions, destructuring, template literals, and the let/const keywords.
Promises and Async/Await Refactor asynchronous code using promises and the async/await syntax.

Embark on a transformative learning experience with our comprehensive course, “Building MicroServices in Java for Cloud .”

Key Highlights

  • Microservices Fundamentals: Gain a solid understanding of microservices architecture, learning how to decompose large applications into smaller, independently deployable services. Explore the principles and benefits that drive the adoption of microservices in modern software development.
  • Java for Microservices : Leverage the power of Java to build robust microservices. Explore Java frameworks and libraries that facilitate the development of scalable and efficient microservices, ensuring seamless integration with cloud platforms.
  • Communication Strategies: Delve into various communication patterns and protocols essential for microservices interactions. Learn about RESTful APIs, messaging queues, and other communication mechanisms used to establish seamless communication between microservices.
  • Software Developers and Engineers
  • System Architects
  • Cloud Enthusiasts
  • Java Developers Exploring Microservices

Basic Programming Problems and Solutions

Here are 10 basic programming problems along with their solutions:

  • Hello World:

Problem: Write a program that prints “Hello, World!” to the console.

Solution (Python):

print(“Hello, World!”)

  • Sum of Two Numbers:

Problem: Write a program that inputs two numbers and prints their sum.

Solution (Java):

import java.util.Scanner;

public class SumOfTwoNumbers {

        Scanner scanner = new Scanner(System.in);

        System.out.print(“Enter first number: “);

        int num1 = scanner.nextInt();

        System.out.print(“Enter second number: “);

        int num2 = scanner.nextInt();

        int sum = num1 + num2;

  • Factorial of a Number:

Problem: Write a program to calculate the factorial of a given number.

Solution (C++):

#include <iostream>

using namespace std;

int factorial(int n) {

    if (n == 0 || n == 1)

        return 1;

        return n * factorial(n – 1);

int main() {

    int num;

    cout << “Enter a number: “;

    cin >> num;

    cout << “Factorial: ” << factorial(num) << endl;

    return 0;

  • Check Even or Odd:

Problem: Write a program that checks if a given number is even or odd.

Solution (JavaScript):

let number = 7;

if (number % 2 === 0) {

    console.log(number + ” is even”);

    console.log(number + ” is odd”);

  • Reverse a String:

Problem: Write a program to reverse a given string.

original_string = “Hello, World!”

reversed_string = original_string[::-1]

print(“Reversed String:”, reversed_string)

  • Fibonacci Series:

Problem: Generate the Fibonacci series up to a specific limit.

public class FibonacciSeries {

        int limit = 10;

        int firstTerm = 0, secondTerm = 1;

        System.out.println(“Fibonacci Series up to ” + limit + ” terms:”);

        for (int i = 1; i <= limit; ++i) {

            System.out.print(firstTerm + “, “);

            int nextTerm = firstTerm + secondTerm;

            firstTerm = secondTerm;

            secondTerm = nextTerm;

  • Check Prime Number:

Problem: Write a program to check if a given number is prime.

def is_prime(number):

    if number > 1:

        for i in range(2, int(number / 2) + 1):

            if (number % i) == 0:

                return False

        else:

            return True

        return False

if is_prime(num):

    print(num, “is a prime number.”)

    print(num, “is not a prime number.”)

  • Find Maximum Element:

Problem: Write a program to find the maximum element in an array.

int findMax(int arr[], int size) {

    int max = arr[0];

    for (int i = 1; i < size; ++i) {

        if (arr[i] > max) {

            max = arr[i];

    return max;

    int numbers[] = {5, 8, 2, 10, 3};

    int size = sizeof(numbers) / sizeof(numbers[0]);

    cout << “Maximum Element: ” << findMax(numbers, size) << endl;

  • Palindrome Check:

Problem: Write a program to check if a given string is a palindrome.

public class PalindromeCheck {

        String str = “level”;

        String reversedStr = new StringBuilder(str).reverse().toString();

        if (str.equals(reversedStr)) {

            System.out.println(str + ” is a palindrome.”);

            System.out.println(str + ” is not a palindrome.”);

  • Count Vowels and Consonants:

Problem: Write a program to count the number of vowels and consonants in a given string.

text = “Hello, World!”

vowels = “AEIOU

Benefits of Solving Basic Programming Problems

Solving basic programming problems offers numerous benefits for individuals looking to enhance their programming skills. Here are some key advantages:

Skill Development:

  • Coding Proficiency: Regular problem-solving helps improve your coding skills and fluency in programming languages.
  • Algorithmic Thinking: It fosters the development of algorithmic thinking, enabling you to devise efficient solutions to various problems.

Logical Thinking:

  • Problem Decomposition: Breaking down problems into smaller components and solving them enhances logical thinking and problem-solving abilities.
  • Pattern Recognition: Regular problem-solving helps in recognizing patterns and similarities between different problems, leading to more efficient solutions.

Learning New Concepts:

  • Exposure to Diverse Topics: Programming problems often cover a wide range of concepts, exposing you to different areas of computer science and software development.
  • New Algorithms and Data Structures: Exploring various problems introduces you to new algorithms and data structures, expanding your knowledge base.

Preparation for Interviews:

  • Technical Interviews: Many technical interviews for programming roles involve solving algorithmic and coding problems. Regular practice prepares you for such interviews and boosts your confidence.
  • Coding Challenges: Familiarity with common coding challenges often encountered in interviews is an asset.

Building a Portfolio:

  • Showcasing Skills: Solving problems allows you to build a portfolio of solutions that you can showcase to potential employers or on coding platforms.
  • GitHub Contributions: Uploading your solutions to platforms like GitHub demonstrates your coding proficiency and problem-solving ability.

Enhanced Efficiency:

  • Code Optimization: Regular practice encourages optimization, leading to more efficient and cleaner code.
  • Time Complexity Awareness: Problem-solving helps in understanding and considering time complexity, contributing to the creation of scalable solutions.

Community Engagement:

  • Online Communities: Engaging in online coding communities allows you to discuss problems, learn from others, and gain insights into alternative solutions.
  • Peer Learning: Collaborating with peers on coding challenges can provide different perspectives and foster a collaborative learning environment.

Career Advancement:

  • Competitive Edge: Building strong problem-solving skills sets you apart in a competitive job market, enhancing your employability.
  • Adaptability: A wide range of problem-solving experiences makes you more adaptable to different tasks and projects.

Personal Satisfaction:

  • Sense of Achievement: Successfully solving programming problems brings a sense of accomplishment, boosting confidence and motivation.
  • Continuous Learning: It fosters a mindset of continuous learning, crucial in a rapidly evolving field like programming.

In summary, regular practice of solving basic programming problems contributes significantly to skill development, logical thinking, and overall proficiency in the field of programming.

For Latest Tech Related Information, Join Our Official Free Telegram Group : PW Skills Telegram Group

What is the Mern Stack Developer? Introduction & Examples

programming for problem solving questions

Defining The Mern Stack Developer The Mern stack developer is gaining popularity among web developers for its ease of use…

What Is the Meaning Of 1LL In C++?

1ll in c++

1LL In C++ denotes a literal constant of type “long long”, representing the integer value 1. It’s commonly used to…

Bootstrap Responsive Table – How to Make Table Responsive in Bootstrap?

bootstrap responsive table

Understanding how to make Bootstrap Responsive Table opens a world of possibilities for web developers, allowing them to create websites…

Leave a Comment Cancel Reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

bottom banner

"Hello World!" in C Easy C (Basic) Max Score: 5 Success Rate: 85.72%

Playing with characters easy c (basic) max score: 5 success rate: 84.40%, sum and difference of two numbers easy c (basic) max score: 5 success rate: 94.62%, functions in c easy c (basic) max score: 10 success rate: 96.00%, pointers in c easy c (basic) max score: 10 success rate: 96.59%, conditional statements in c easy c (basic) max score: 10 success rate: 96.95%, for loop in c easy c (basic) max score: 10 success rate: 93.74%, sum of digits of a five digit number easy c (basic) max score: 15 success rate: 98.67%, bitwise operators easy c (basic) max score: 15 success rate: 94.96%, printing pattern using loops medium c (basic) max score: 30 success rate: 95.94%, cookie support is required to access hackerrank.

Seems like cookies are disabled on this browser, please enable them to open this website

  • C Programming Home
  • ▼C Programming Exercises
  • Basic Declarations and Expressions
  • Basic Part-II
  • Basic Algorithm
  • Variable Type
  • Input - Output
  • Conditional Statements
  • Do-While Loop
  • Linked List
  • Callback function
  • Variadic function
  • Inline Function
  • File Handling
  • Searching and Sorting
  • C Programming Exercises, Practice, Solution

What is C Programming Language?

C is a general-purpose, imperative computer programming language, supporting structured programming, lexical variable scope and recursion, while a static type system prevents many unintended operations. C was originally developed by Dennis Ritchie between 1969 and 1973 at Bell Labs. It has since become one of the most widely used programming languages of all time, with C compilers from various vendors available for the majority of existing computer architectures and operating systems.

The best way we learn anything is by practice and exercise questions. We have started this section for those (beginner to intermediate) who are familiar with C programming.

Hope, these exercises help you to improve your C programming coding skills. Currently, following sections are available, we are working hard to add more exercises. Please refer to this page for important C snippets, code, and examples before starting the exercises. Happy Coding!

List of C Programming Exercises :

  • Basic Declarations and Expressions [ 150 Exercises with Solution ]
  • Basic Part-II [ 7 Exercises with Solution ]
  • Basic Algorithm [ 75 Exercises with Solution ]
  • Variable Type [ 18 Exercises with Solution ]
  • Input, Output [ 10 Exercises with Solution ]
  • Conditional Statement [ 26 Exercises with Solution ]
  • While Loop [ 11 Exercises with Solution ]
  • Do-While Loop [ 12 Exercises with Solution ]
  • For Loop [ 61 Exercises with Solution ]
  • Array [ 107 Exercises with Solution ]
  • Structure [ 9 Exercises with Solution ]
  • Pointer [ 22 Exercises with Solution ]
  • Linked List [ 64 Exercises with Solution ]
  • Stack [ 17 Exercises with Solution ]
  • Binary Heap (Tree-Based Structure) [ 9 Exercises with Solution ]
  • Queue [ 13 Exercises with Solution ]
  • Hash [ 10 Exercises with Solution ]
  • Tree [ 10 Exercises with Solution ]
  • Graph [ 10 Exercises with Solution ]
  • Numbers [ 38 Exercises with Solution ]
  • Math [ 38 Exercises with Solution ]
  • String [ 41 Exercises with Solution ]
  • Date Time [ 10 Exercises with Solution ]
  • Function [ 12 Exercises with Solution ]
  • Callback Function [ 11 Exercises with Solution ]
  • Variadic Function [ 8 Exercises with Solution ]
  • Inline Function [ 11 Exercises with Solution ]
  • Recursion [ 21 Exercises with Solution ]
  • File Handling [ 19 Exercises with Solution ]
  • Search and Sorting [ 31 Exercises with Solution ]
  • Challenges [ 35 exercises with solution ]
  • C Snippets [29]
  • More to Come !

[ Want to contribute to C exercises? Send your code (attached with a .zip file) to us at w3resource[at]yahoo[dot]com. Please avoid copyrighted materials.]

Do not submit any solution of the above exercises at here, if you want to contribute go to the appropriate exercise page.

Popularity of Programming Language Worldwide, Nov 2023 compared to a year ago:

`
Rank Change Language Share Trend
1 Python 27.99 % +0.0 %
2 Java 15.91 % -0.8%
3 Javascript 9.18 % -0.3%
4 C/C++ 6.76 % +0.2%
5 C# 6.67 % -0.3 %
6 PHP 4.86 % -0.3 %
7 R 4.45% +0.4%
8 TypeScript 2.95 % +0.1%
9 Swift 2.7 % +0.6%
10 Objective-C 2.32% +0.2%
11 Rust1.98% +0.3%
12 Go 1.98% -0.0%
13 Kotlin 1.76 % -0.1%
14 Matlab 1.6 % +0.0%
15 Ada 1.02% +0.2%
16 Ruby 1.0 % -0.1 %
17 Dart 0.99 % +0.1 %
18 Powershell 0.93 % +0.0 %
19 VBA 0.93 % -0.1 %
20 Scala 0.62 % -0.1 %
21 Lua 0.62 % 0.0 %
22 Abap 0.58 % +0.1 %
23 Visual Basic 0.55 % -0.1 %
24 Julia 0.35 % -0.0 %
25 Groovy 0.31 % -0.1 %
26 Perl 0.31 % -0.1 %
27 Haskell 0.27 % -0.0 %
28 Cobol 0.25 % -0.1 %
29 Delphi/Pascal 0.18 % +0.2 %

Source : https://pypl.github.io/PYPL.html

TIOBE Index for November 2023

Nov 2023 Nov 2022 Change Programming Language Ratings Change
1 1 Python 14.16% -3.02%
2 2 C 11.77% -3.31%
3 4 C++ 10.36% -0.39%
4 3 Java 8.35% -3.63%
5 5 C# 7.65% +3.40%
6 7 JavaScript 3.21% +0.47%
7 10 PHP 2.30% +0.61%
8 6 Visual Basic 2.10% -2.01%
9 9 SQL 1.88% +0.07%
10 8 Assembly language 1.35% -0.83%
11 17 Scratch 1.31% +0.43%
12 24 Fortran 1.30% +0.74%
13 11 Go 1.19% +0.05%
14 15 MATLAB 1.15% +0.14%
15 28 Kotlin 1.15% +0.68%
16 14 Delphi/Object Pascal 1.14% +0.07%
17 18 Swift 1.04% +0.17%
18 19 Ruby 0.99% +0.14%
19 12 R 0.93% -0.20%
20 20 Rust 0.91% +0.16%

Source : https://www.tiobe.com/tiobe-index/

List of Exercises with Solutions :

  • HTML CSS Exercises, Practice, Solution
  • JavaScript Exercises, Practice, Solution
  • jQuery Exercises, Practice, Solution
  • jQuery-UI Exercises, Practice, Solution
  • CoffeeScript Exercises, Practice, Solution
  • Twitter Bootstrap Exercises, Practice, Solution
  • C# Sharp Programming Exercises, Practice, Solution
  • PHP Exercises, Practice, Solution
  • Python Exercises, Practice, Solution
  • R Programming Exercises, Practice, Solution
  • Java Exercises, Practice, Solution
  • SQL Exercises, Practice, Solution
  • MySQL Exercises, Practice, Solution
  • PostgreSQL Exercises, Practice, Solution
  • SQLite Exercises, Practice, Solution
  • MongoDB Exercises, Practice, Solution

Follow us on Facebook and Twitter for latest update.

  • Weekly Trends and Language Statistics

Codility Logo

Programming Problem-Solving Interview Questions You Should Ask

Be the first to know.

Sign up for a weekly dose of tech hiring news and updates.

At Codility, we create coding assessments for hiring software developers.

This implies that we also hire developers to create technical interviews for hiring developers. It is like two-star pointers or programming squared.

Our interview process consists of a Codility coding assessment in the front, and then a good old technical interview for the candidates who prove they have the coding knowledge and fundamentals in the back. I want to share four technical interview tips and questions that we use to assess competencies in programming during a video interview, using CodeLive.

Coding assessments and remote technical interviews

1. Scalability & Optimization

If you are planning to do something big, it will need to scale well in this way or another. A basic understanding of scalability is assessed by an automated Codility assessment .

During the technical interview process, we ask candidates to answer a simple programming problem-solving question which has multiple solutions with different simplicity/scalability trade-offs (e.g. compute prefix sums of a sequence of numbers). We assess whether a candidate notices the scalability aspect and whether he/she can deliver the working solution with better scalability.

Time permitting we probe deeper, asking “can it possibly be done better?” This question opens discussions about possible optimizations, sometimes going down to the hardware level, but also about intrinsic limitations of computing machinery, which greatly illustrates whether candidate a can apply theory to a concrete problem.

2. Aliasing – Pointers & References

In the interview process, we usually ask candidates to answer a simple programming problem-solving question that involves pointers/references, like manipulations on single-link lists. As much as we rarely deal with direct lists manipulation nowadays, we believe it shows whether a candidate can deal with real-life scenarios where multiple levels of indirection occur e.g. in data models. (And as David Wheeler used to say, “All problems in computer science can be solved by another level of indirection, except of course for the problem of too many indirections.”)

3. Recursion – Be Mentally Prepared

Understanding and handling recursion is a sign of a programmer’s fitness, and this should be a key component of any coding assessment.

On some jobs this skill will be crucial, on other jobs maybe not so much, but the fact that a candidate knows how to do it shows that they’ve been doing mental push-ups and sit-downs long enough to be ready to take the triathlon challenge and showcase their strength throughout the interview process.

The classic moderate question here is to take a simple recursive function and ask the candidate to rewrite it into an iterative one.

4. Communication – Be Clear & Concise

Coding is not only a way of communicating your requirements to the machine, but also a way of communicating your intent to fellow team members.

For each programming exercise the candidates solve, both on the automated Codility coding assessments, online CodeLive video interview, and in face-to-face interviews, we look at the code they write and assess whether it speaks to us clearly. If you look at the code and you immediately know what’s going on, that’s a plus, if you don’t that’s a red flag.

Greg is the founder and principal scientist at Codility.

Connect on LinkedIn

Forage

Programming Interview Questions

How to prepare for programming interview questions, forage find, conceptual coding interview questions, how to prepare for conceptual coding interview questions, general coding interview questions, how to prepare for general coding interview questions, common coding interview questions: the bottom line, 45 common coding interview questions.

Zoe Kaplan

  • Share on Twitter Share on Twitter
  • Share on Facebook Share on Facebook
  • Share on LinkedIn Share on LinkedIn

student coding on laptop

Forage puts students first. Our blog articles are written independently by our editorial team. They have not been paid for or sponsored by our partners. See our full  editorial guidelines .

Table of Contents

A coding interview can be nerve-racking, but it’s an essential part of the technical interview process to demonstrate your programming skills and knowledge of coding concepts. While the exact questions a technical recruiter might ask vary depending on what kind of role you’re applying for, there are some common coding interview questions you can prepare for to ace the interview. We’ll review the three main types of questions you’ll encounter during a coding interview and how to prepare for them. 

A coding interview typically starts with an assessment of your computer programming skills. You’ll need to answer questions that demonstrate you know how to do specific tasks or functions, usually through an assessment called a whiteboard challenge or independent coding test.

>>MORE: Are Coding Bootcamps Worth It in 2024?

What questions will you get in a whiteboard challenge or independent coding test? Here are some examples:

  • How do you reverse a string?
  • How do you determine if a string is a palindrome?
  • How do you calculate the number of numerical digits in a string?
  • How do you find the count for the occurrence of a particular character in a string?
  • How do you find the non-matching characters in a string?
  • How do you find out if the two given strings are anagrams?
  • How do you calculate the number of vowels and consonants in a string?
  • How do you total all of the matching integer elements in an array?
  • How do you reverse an array?
  • How do you find the maximum element in an array?
  • How do you sort an array of integers in ascending order?
  • How do you print a Fibonacci sequence using recursion?
  • How do you calculate the sum of two integers?
  • How do you find the average of numbers in a list?
  • How do you check if an integer is even or odd?
  • How do you find the middle element of a linked list?
  • How do you remove a loop in a linked list?
  • How do you merge two sorted linked lists?
  • How do you implement binary search to find an element in a sorted array?
  • How do you print a binary tree in vertical order?

There are two main types of assessments for programming interview questions: a whiteboard challenge and a coding test. 

How to Prepare for a Whiteboard Challenge

A whiteboard challenge is when you’re given a coding challenge during a live interview . You solve the problem in front of the interviewer and explain your process as you work on the challenge.

You can use the UMPIRE method to approach these problems:

U: Understand the problem M: Match the problem with the interviewer P: Plan your approach and solution I: Implement your solution R: Review your solution E: Evaluate your solution

To prepare for a whiteboard challenge, “practice talking through your problem-solving process ,” says Archie Payne, president of CalTek Staffing, an IT and technical staffing firm. “Interviewers don’t just want to see that candidates can complete the test task, they also want to get insights into how candidates approach the process. A good way to prepare is to pretend you’re teaching a programming class, and practice how you’d explain and demonstrate key concepts to someone who doesn’t know them.”

It’s less about solving everything right the first time (or even at all) and more about learning how you approach problems and solve challenges. 

>>MORE: 13 Best Free Coding Bootcamps in 2024

And what happens if you don’t know the answer? Don’t panic.“Be honest that this is a gap in your knowledge,” Payne says. “Take a moment to think critically about the problem and the ways you’d likely approach it, then explain that process to the interviewer. Hiring managers don’t necessarily expect entry-level candidates to have all the answers, but they do want to hire someone who’s self aware about what they do and don’t know, and willing to learn and try new things.”

programming for problem solving questions

LeetCode is a great resource for practicing these types of questions. You can create a free account and practice hundreds of coding questions you might get in an interview.

How to Prepare for an Independent Coding Test

An independent coding test focuses on your ability to code and solve problems within a given time frame. You may have an independent coding test after your whiteboard test or before as part of a screening. 

The company will give you a link to a common code editor, and you can choose what programming language you want to write in. Before you start the test, you’ll know how long you have to complete it and whether you’ll be able to leave the platform during the test. Make sure you do the test in a quiet environment where you won’t have distractions.

To prepare for this part of the interview, “​​simulate interview conditions,” Mohit Maheshwari, co-founder at NMG Technologies, a full-service IT company, says. “Practice coding on a whiteboard or a blank sheet of paper, as this is how you will be doing it during the interview. Get used to writing code without the aid of an IDE [integrated development environment] or compiler.” 

Need to practice your coding skills? A Forage job simulation can help you build the skills you need to ace the interview — and give you experience you can talk about during the interview. 

Basic programming, Python, Git, React
Java, RESTful Web Development, HTTP
Data structures, object-oriented design, code analysis, code readability
Data modeling, system design, Java, Spring
Python, cloud security
System design, Java, APIs

The recruiter or hiring manager will also ask conceptual coding interview questions to learn whether you’re familiar with the concepts you’ll be working with. 

“Expect questions on basic data structures such as arrays, linked lists, trees, and graphs, as well as common algorithms like sorting and searching,” Maheshwari says.

Examples of these questions include:

  • What is a data structure?
  • What is an array?
  • What is a linked list?
  • What is the difference between an array and a linked list?
  • What is LIFO? 
  • What is FIFO?
  • What is a stack?
  • What are binary trees?
  • What are binary search trees?
  • What is object-oriented programming?
  • What is the purpose of a loop in programming?
  • What is a conditional statement?
  • What is debugging?
  • What is recursion?
  • What are the differences between linear and non-linear data structures?

Preparing for conceptual coding interview questions requires two focuses: knowing the concepts, then knowing how to explain them.

First, refamiliarize yourself with these concepts. If you studied coding at school, look through your notes, textbooks, and past exams to make sure you understand each concept. Be sure you not only know the definition of the concept, but how to put that concept into context; memorizing index card definitions isn’t the goal.

Then, you can practice by explaining them clearly to someone who doesn’t have technical knowledge. While the recruiter or hiring manager you talk to should have basic technical know-how, explaining the term to someone without it ensures you really know the ins and outs of the concept because you have to break it down very clearly.

Knowing how to explain complex technical terms to non-technical people is also a soft skill that employers look for — be sure to show this skill off in the interview!

>>MORE: Learn explanations of common software engineering technical concepts with entry-level software engineering interview questions (and answers) .

Outside of programming questions and questions about technical concepts, you might answer questions about your general experience, like how you learned to code, behavioral interview questions , and how you keep your skills fresh. 

Examples of general common coding interview questions include:

  • What programming languages do you have experience working with?
  • Describe a time you faced a challenge in a project you were working on and how you overcame it.
  • Walk me through a project you’re currently or have recently worked on.
  • Give an example of a project you worked on where you had to learn a new programming language or technology. How did you go about learning it?
  • How do you ensure your code is readable by other developers?
  • What are your interests outside of programming?
  • How do you keep your skills sharp and up to date?
  • How do you collaborate on projects with non-technical team members?
  • Tell me about a time when you had to explain a complex technical concept to a non-technical team member.
  • How do you get started on a new coding project?

Preparing for general coding interview questions is similar to how you might prepare for any other interview: reviewing your experience and preparing to talk about specific situations you’ve navigated in the workplace. 

“Be prepared to explain your expertise in the languages you know and what types of projects you’ve completed using them,” Payne says. “​​The ability to troubleshoot and correct issues as you go is a key skill for programmers at all career levels. The best answer will focus on the steps you take to diagnose and fix issues, rather than the intricate details of the specific problem you’re describing.”

programming for problem solving questions

Interview Preparation: Own Your Story

Learn how to identify your strengths, ask memorable questions in an interview, and share your experience effectively.

Avg. Time: 3-4 hours

Skills you’ll build: Storytelling, career and self development, interview preparation

It’s OK if you don’t have any prior professional experience. You can still draw from examples in the classroom, at an internship , or working on an independent project. 

Programming interview questions generally come in three different forms: practical coding tests, questions about technical concepts, and general questions about your experience. To ace a coding interview, prepare carefully for each section: practice problems, review concepts, and use the STAR method to shape answers about your experience.

Are you getting ready for a coding interview? Practice sample coding problems with matrices and arrays and learn what hiring managers look for in technical interviews with Girls Who Code’s Technical Interview Prep .

Zoe Kaplan

Related Posts

Interview angst here’s what not to say in an interview, how to prep for consulting interview questions, 11 financial analyst interview questions (and answers), upskill with forage.

working at Accenture

Gain job skills you can talk about in interviews.

Table of Contents

Coding interview questions on conceptual understanding, programming interview questions, choose the right software development program, get ahead of the curve and master programming today, top 40 coding interview questions you should know.

Top 40 Coding Interview Questions You Should Know

Programming questions are an integral part of an interview for the developer's position. No matter which programming language you master, familiarity with fundamental concepts of programming is something that is always expected from you.

Coding skills are always the deciding factor in any programming interview. In this coding interview questions article, we will discuss the top 40 Coding Interview Questions you should absolutely know to crack those interviews and get your dream job.

So without further ado, let’s get started!

Watch the video below that deals with real-time and corporate-level programming-based interview questions and answers.

The coding interview questions addresses in this article are grouped into 2 categories (as below) to make your learning simpler.

  • Conceptual Interview Questions

We will now look at the first category of coding interview questions. 

This section covers some coding interview questions that test the conceptual understanding of the candidate.

1. What is a Data Structure?

  • A data structure is a storage format that defines the way data is stored, organized, and manipulated.
  • Some popular data structures are Arrays, Trees, and Graphs.

Become a Software Development Professional

Full stack java developer.

  • Kickstart Full Stack Java Developer career with industry-aligned curriculum by experts
  • Hands-on practice through 20+ projects, assessments, and tests

Full Stack Web Developer - MEAN Stack

  • Comprehensive Blended Learning program
  • 8X higher interaction in live online classes conducted by industry experts

2. What is an Array?

  • An array is commonly referred to as a collection of items stored at contiguous memory locations.
  • Items stored are of the same type.
  • It organizes data so that a related set of values can be easily sorted or searched.

array string

3. What is a Linked List?

  • Like an array, a linked list refers to a linear data structure in which the elements are not necessarily stored in a contiguous manner.
  • It is basically a sequence of nodes, each node points towards the next node forming a chain-like structure.

linked list

Fig: Linked List

4. What is LIFO?

  • LIFO is an abbreviation for Last In First Out
  • It is a way of accessing, storing and retrieving data.
  • It extracts the data that was stored last first.

5. What is a Stack?

  • A stack refers to a linear data structure performing operations in a LIFO (Last In First Out) order.
  • In a stack, elements can only be accessed, starting from the topmost to the bottom element.

6. What is FIFO?

  • FIFO stands for First In First Out.
  • The data that was stored first is extracted first.

lifo fifo

Fig: LIFO, FIFO

Till now, you’ve covered some very fundamental coding interview questions. Going ahead you will dive deeper into the subject.

7. What is a Queue?

  • A queue refers to a linear data structure that performs operations in a FIFO order.
  • In a queue, the least recently added elements are removed first as opposed to a stack. 

queue

8. What are Binary Trees?

  • A binary tree is an extension of the linked list structure where each node has at most two children. 
  • A binary tree has two nodes at all times, a left node and a right node.

binary-tees

Fig: Binary Trees

9. What is Recursion?

  • Recursion refers to a function calling itself based on a terminating condition.
  • It uses LIFO and therefore makes use of the stack data structure.

The next couple of coding interview questions will explore your knowledge of OOPs.

10. What is the OOPs concept?

OOPs stands for Object-Oriented Programming System, a paradigm that provides concepts such as objects, classes, and inheritance.

11. What are the concepts introduced in OOPs?

Following are the concepts introduced in OOPs:

  • Object - A real-world entity having a particular state and behavior. We can define it as an instance of a class.
  • Class - A logical entity that defines the blueprint from which an object can be created or instantiated.
  • Inheritance - A concept that refers to an object gaining all the properties and behaviors of a parent object. It provides code reusability.
  • Polymorphism - A concept that allows a task to be performed in different ways. In Java, we use method overloading and method overriding to achieve polymorphism.
  • Abstraction - A concept that hides the internal details of an application and only shows the functionality. In Java, we use abstract class and interface to achieve abstraction.
  • Encapsulation - A concept that refers to the wrapping of code and data together into a single unit.

This is one of the very common coding interview questions, that often allows the interviewer to branch out into related topics based on the candidate’s answers

12. Explain what a Binary Search Tree is.

  • A binary search tree is used to store data in a manner that it can be retrieved very efficiently. 
  • The left sub-tree contains nodes whose keys are less than the node’s key value.
  • The right sub-tree contains nodes whose keys are greater than or equal to the node’s key value

binary search

Fig: Binary Search Tree

13. Explain Doubly Linked Lists?

  • Doubly linked lists are categorized as a special type of linked list in which traversal across the data elements can be done in both directions. 
  • This is made possible by the presence of two links in every node, one that links to the node next to it and another that connects to the node before it.

doubly link

Fig: Doubly Linked List

14. What is a Graph?

  • A graph is a particular type of data structure that contains a set of ordered pairs.
  • The ordered pairs in a graph are also known as edges or arcs and are most commonly used to connect nodes where the data can be stored and retrieved.

15. Differentiate between linear and non-linear data structure?

It is a structure in which data elements are adjacent to each other

It is a structure in which each data element can connect to over two adjacent data elements

Examples of linear data structure include linked lists, arrays, queues, and stacks

Examples of nonlinear data structure include graphs and trees

16. What is a Deque?

  • A deque is a double-ended queue.
  • This is a structure in which elements can be inserted or removed from either end.

17. What’s the difference between Stack and Array ?

Stack

Array

Stack follows a Last In First Out (LIFO) pattern. What this means is that data access necessarily follows a particular sequence where the last data to be stored is the first one that will be extracted.

On the other hand, Arrays do not follow a specific order, but instead can be accessed or called by referring to the indexed element within the array.

18. Which sorting algorithm is the best?

  • There are many types of sorting algorithms: bubble sort, quick sort, balloon sort, merge sort, radix sort, and more.
  • No algorithm can be considered as the best or fastest because they have designed each for a specific type of data structure where it performs the best

19. How does variable declaration affect memory?

  • The amount of memory that is to be reserved or allocated depends on the data type being stored in that variable. 
  • For example, if a variable is declared to be “integer type”, 32 bits of memory storage will then be reserved for that particular variable.

20. What are dynamic data structures?

Dynamic data structures have the feature where they expand and contract as a program runs. It provides a very flexible method of data manipulation because adjusts based on the size of the data to be manipulated.

These 20 coding interview questions that test the conceptual understanding of the candidates give the interview a clear idea on how strong the candidate’s fundamentals are

The next set of coding interview questions focus tests the programming expertise of the candidates and dives deep into various related aspects.

The code screenshots given along with the below coding interview questions helps you provide the answer to the question, with clarity.

21. How do you reverse a string in Java?

  • Declare a string.
  • Take out the length of that string.
  • Loop through the characters of the string.
  • Add the characters in reverse order in the new string.

22. How do you determine if a string is a palindrome?

  • A string is a palindrome when it stays the same on reversing the order of characters in that string.
  • It can be achieved by reversing the original string first and then checking if the reversed string is equal to the original string.

23. Find the number of occurrences of a character in a String?

To find the number of occurrences, loop through the string and search for that character at every iteration; whenever it is found, it will update the count.

24. How to find out if the given two strings are anagrams or not?

Two strings are anagrams if they contain a similar group of characters in a varied sequence.

  • Declare a boolean variable that tells at the end of the two strings are anagrams or not.
  • First, check if the length of both strings is the same, if not, they cannot be anagrams.
  • Convert both the strings to character arrays and then sort them.
  • Check if the sorted arrays are equal. If they are equal, print anagrams, otherwise not anagrams. 

boolean anagrmstat = false;

if (str.length() != reverse.length()) {

    System.out.println(str + " and " + reverse + " not anagrams string");

    char[] anagram1 = str.toCharArray();

    char[] anagram2 = reverse.toCharArray();

    Arrays.sort(anagram1);

    Arrays.sort(anagram2);

    anagrmstat = Arrays.equals(anagram1, anagram2);

if (anagrmstat == true) {

    System.out.println(" anagrams string");

    System.out.println(" not anagrams string");

25. How do you calculate the number of vowels and consonants in a String?

  • Loop through the string.
  • Increase the vowel variable by one whenever the character is found to be a vowel, using the if condition. Otherwise, increment the consonant variable.
  • Print the values of both the vowel and the consonant count.

int vowels = 0;

int consonants = 0;

for (int k = 0; k < str.length(); k++) {

    char c = str.charAt(k);

    if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')

        vowels++;

        consonants++;

System.out.println("Vowel count is " + vowels);

System.out.println("Consonant count is: " + consonants);

26. How do you get the matching elements in an integer array?

  • Declare an array.
  • Nest a couple of loops to compare the numbers with other numbers in the array.
  • Print the matching elements if found.

int[] a = { 1, 2, 3, 4, 5, 1, 2, 6, 7 };

for (int m = 0; m < a.length; m++) {

    for (int n = m + 1; n < a.length; n++) {

        if (a[m] == a[n])

            System.out.print(a[m]);

27. How would you implement the bubble sort algorithm?

  • Nest a couple of loops to compare the numbers in the array.
  • The array will be sorted in ascending order by replacing the elements if found in any other order.

int[] a = { 1, 2, 7, 6, 4, 9, 12 };

for (int k = 0; k < a.length; k++) {

    for (int l = 0; l < a.length - l - 1; l++) {

        if (a[l] > a[l + 1]) {

            int t = a[l];

            a[l] = a[l + 1];

            a[l + 1] = t;

Learn the top skills in-demand including Angular, Spring Boot, JSPs, and SOA to build highly web scalable apps with the Full Stack Java Developer Masters Program .

28. How would you implement the insertion sort algorithm?

  • We assume the first element in the array to be sorted. The second element is stored separately in the key. This sorts the first two elements. You can then take the third element and do a comparison with the ones on the left of it. This process will go on until a point where we sort the array.

for (int m = 1; m < a.length; m++) {

    int n = m;

    while (n > 0 && a[n - 1] > a[n]) {

        int k = a[n];

        a[n] = a[n - 1];

        a[n - 1] = k;

        n--;

29. How do you reverse an array?

  • Loop till the half-length of the array.
  • Replace the numbers corresponding to the indexes from the starting and the end.

for (int t = 0; t < a.length / 2; t++) { 

    int tmp = a[t]; 

    a[t] = a[a.length - t - 1]; 

    a[a.length - t- 1] = tmp; 

30. How would you swap two numbers without using a third variable?

  • Declare two variables and initialize them with values.
  • Make b the sum of both numbers.
  • Then subtract the sum (b) from a, so a is now swapped.
  • Lastly, subtract a from the sum (b), so b is also swapped.

int a = 10;

int b = 20;

b = b + a; // now b is sum of both the numbers

a = b - a; // b - a = (b + a) - a = b (a is swapped)

b = b - a; // (b + a) - b = a (b is swapped)

31. Print a Fibonacci series using recursion?

  • The Fibonacci numbers are the numbers in the following integer sequence:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ……..

  • We can calculate them using the mathematical formula used in the Fibonacci recursive function.

public static int fibonacci(int n) {

    if (n <= 1)

        return n;

    return fibonacci(n - 1) + fibonacci(n - 2);

public static void main(String args[]) {

    int n = 10;

    System.out.println(fibonacci(n));

32. How do you find the factorial of an integer?

  • A factorial is a function that multiplies a number by every number below it. For example, 5!= 5*4*3*2*1=120.
  • Recursive function multiples the numbers until it reaches 1.

public static long factorial(long n) {

if (n == 1)

    return 1;

    return (n * factorial(n - 1));

33. How do you reverse a Linked List?

  • Declare a linked list.
  • Add elements to that linked list.
  • Apply the descending iterator method to the linked list.
  • This reverses the order of elements in the linked list.

LinkedList<Integer> ll = new LinkedList<>();

System.out.println(ll);

LinkedList<Integer> ll1 = new LinkedList<>();

ll.descendingIterator().forEachRemaining(ll1::add);

System.out.println(ll1);

34. How would you implement Binary Search?

  • Binary search divides the array into half in every iteration step until it finds the element.
  • It works on the sorted arrays since it compares the values of adjacent elements and then calculates the mid number.
  • If the value of low becomes greater than high at any point, it means the element is not present in the list.

int mid = (low + high) / 2;

while (low <= high) {

    if (arr[mid] < key) {

        low = mid + 1;

    } else if (arr[mid] == key) {

        return mid;

    } else {

        high = mid - 1;

    mid = (low + high) / 2;

if (low > high) {

    return -1;

35. How would you find the second largest number in an array?

  • Loop through the array.
  • If the value of i is greater than the highest, store the value of i in highest, and store the value of highest in the second-highest variable.

private static int findSecondHighest(int[] array) {

    int highest = Integer.MIN_VALUE;

    int secondHighest = Integer.MIN_VALUE;

    for (int i : array) {

        if (i > highest) {

            secondHighest = highest;

            highest = i;

        } else if (i > secondHighest) {

            secondHighest = i;

    return secondHighest;

36. How do you remove all occurrences of a given character from the input string?

  • Use the built-in string method “replace” to replace a character with any other character, including symbols and white spaces.

String str1 = "Australia";

str1 = str1.replace("a", "");

System.out.println(str1); // ustrli

37. Showcase Inheritance with the help of a program?

  • The class Cat inherits the property color from the class Animal by extending the parent class (Animal).
  • This way a class Cat can have more parent classes if it wishes to inherit their properties.

class Animal {

    String color;

class Cat extends Animal {

    void meow() {

        System.out.println("Meow");

38. Explain overloading and overriding with the help of a program?

Overloading:

When a class has two or more methods with the same name, they are called overloaded methods.

class Foo {

    void print(String s) {

        System.out.println(s);

    void print(String s, int count) {

        while (count > 0) {

            System.out.println(s);

            count--;

Overriding:

When a superclass method is also implemented in the child class, it’s a case of overriding.

class Base {

    void printName() {

        System.out.println("Base Class");

class Child extends Base {

    @Override

        System.out.println("Child Class");

39. How do you check if the given number is prime?

  • Use if statements to check for each condition separately:
  • If the number is 0 or 1, it cannot be prime.
  • If the number is 2, it is prime number.
  • If the number is indivisible by other numbers, it is prime.

public static boolean isPrime(int n) {

    if (n == 0 || n == 1) {

        return false;

    if (n == 2) {

        return true;

    for (int i = 2; i <= n / 2; i++) {

        if (n % i == 0) {

            return false;

    return true;

40. How do you sum all the elements in an array?

  • Use for loop to iterate through the array and keep adding the elements in that array.

int[] array = { 1, 2, 3, 4, 5 };

int sum = 0;

for (int i : array)

    sum += i;

System.out.println(sum);

As you get prepared for your job interview, we hope that these Coding Interview Questions have provided more insight into what types of questions you are likely to come across.

This table compares various courses offered by Simplilearn, based on several key features and details. The table provides an overview of the courses' duration, skills you will learn, additional benefits, among other important factors, to help learners make an informed decision about which course best suits their needs.

Program Name Full Stack Java Developer Automation Testing Masters Program Geo IN All University Simplilearn Simplilearn Course Duration 6 Months 11 Months Coding Experience Required Basic Knowledge Basic Knowledge Skills You Will Learn 15+ Skills Including Core Java, SQL, AWS, ReactJS, etc. Java, AWS, API Testing, TDD, etc. Additional Benefits Interview Preparation Exclusive Job Portal 200+ Hiring Partners Structured Guidance Learn From Experts Hands-on Training Cost $$ $$ Explore Program Explore Program

Now that you are well-versed with the top Coding Interview Questions, you should be seeking out opportunities to gain the skills you need to leverage the immense popularity of software development and build a successful career in it. Well, you needn’t look any further. We have got your back! Our comprehensive  Full Stack Developer Course  will help you with the necessary skills and more that you need and help you become career-ready upon completion. 

If you are looking for more information, do check out our YouTube video that further explains these coding interview questions and answers, and helps you become more confident while appearing for the interview processes.

Embarking on a journey to become a full-fledged full stack developer involves diving into a broad range of coding concepts, from frontend technologies like HTML, CSS, and JavaScript, to backend systems including server, database, and application logic. To ensure you're well-prepared for your coding interviews, consider enrolling in a full stack developer course that covers essential interview questions and provides comprehensive training.

Do you have any questions for us? Well, feel free to mention them in the comments section of this “Top 40 Coding Interview Questions’’ article. Our subject matter experts will review and answer them for you soon.

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees

Cohort Starts:

4 Months€ 2,499
9 Months€ 2,199

Cohort Starts:

6 Months€ 1,500

Cohort Starts:

11 Months€ 1,099

Cohort Starts:

6 Months€ 1,500

Recommended Reads

Kubernetes Interview Guide

Top R Programming Interview Questions and Answers

180+ Core Java Interview Questions and Answers for 2024

Apache Spark Interview Guide

Top Meta (Facebook) Interview Questions and Answers for 2024

Top 100+ Git Interview Questions [2024]: Crack the Code

Get Affiliated Certifications with Live Class programs

Automation testing masters program.

  • Comprehensive blended learning program
  • 200 hours of Applied Learning
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.

Top 100+ SQL Interview Questions and Practice Exercises

Author's photo

  • jobs and career
  • sql practice
  • sql interview questions

Table of Contents

Review Your SQL Knowledge

Practice regularly, familiarize yourself with the testing platform, prepare for different types of questions, additional tips, explore 55+ general sql interview questions, practice, practice, practice, …, sql cheat sheet, data analysis in sql, window functions, common table expressions, advanced sql, good luck with your interview.

Are you gearing up for a SQL interview? This article is packed with over 100 SQL interview questions and practical exercises, organized by topic, to help you prepare thoroughly and approach your interview with confidence.

SQL is essential for many jobs, like data analysis, data science, software engineering, data engineering, testing, and many others. Preparing well for a SQL interview is crucial, no matter what role you're aiming for.

Searching for a new job can be really stressful, whether you're choosing to switch, have been laid off, or are looking for your first job. That's why being well-prepared is essential.

In this article, I've gathered over 100 SQL interview questions and exercises. These questions are spread across various articles published at LearnSQL.com. I have organized the articles by topic. Feel free to explore only the topics related to your specific job. I've also included tips to help you prepare for your interview.

SQL Interview Preparation Tips

Start preparing for your SQL interview well in advance. Once you're invited to an interview (Congratulations!), ask your recruiter what to expect and what is the format of the interview. For the SQL part you can usually expect coding exercises on an automated testing platform, a take-home assignment, or a whiteboard session.

The key to performing well in a SQL interview is practice. You'll likely be nervous, so the more familiar you are with SQL, the more instinctive your responses will become. Practice a variety of SQL problems so that querying becomes second nature to you.

If your interview involves using a specific coding platform, try to get comfortable with it beforehand. Many platforms offer a demo or practice session, so take advantage of this feature to familiarize yourself with the interface. This familiarity can help reduce stress and improve your performance during the actual interview.

Illustration: Person during an interview

  • Coding Platform Questions: Whether during the interview or as a take-home task, make sure you understand the typical questions and problems that might appear on these platforms. Practice solving similar problems under timed conditions.
  • Whiteboard Interviews: Be ready to write code in pseudocode and discuss your thought process. Focus on explaining the concepts and logic behind your solutions more than the exact syntax, which demonstrates a deeper understanding of the problem-solving process.
  • Review Key SQL Concepts: Make sure you're comfortable with all fundamental SQL operations such as joins, subqueries, window functions, and aggregation. Also, review more advanced topics if the job role demands it.
  • Mock Interviews: Consider doing mock interviews with friends or mentors to simulate the interview environment. This practice can help you manage time and stress effectively.
  • Rest Well: Ensure you're well-rested before the interview day; a clear mind will help you think and perform better.

By incorporating these strategies into your preparation, you can approach your SQL interview with confidence and increase your chances of success.

Begin by refreshing your SQL knowledge, particularly if you haven't used it in a while. In this section we have collected some resources to assist you.

Our "SQL Basics" course is perfect for beginners or anyone needing a brief review. It covers both basic and intermediate SQL topics. In this course, you will actively write SQL code in various exercises, which will help you grow more confident in your SQL skills as you advance.

Illustration: SQL Basics course

After you have refreshed the basics, check out these articles filled with SQL interview questions to help you prepare:

  • Complete SQL Practice for Interviews — includes 16 SQL interview questions with practical exercises.
  • 16 SQL Interview Questions for Business Analysts — SQL interview questions tailored for analysts.
  • 8 Common Entry Level SQL Developer Interview Questions — great for beginners.
  • Top 15 SQL Interview Questions in 2021 — a compilation of recent and relevant questions.

After refreshing your SQL skills, it’s important to keep practicing. Interviews can be stressful, and even straightforward topics can become challenging under pressure. The more you practice, the more confidently you can handle questions and problem-solving during an interview.

Here are some practice resources we recommend:

  • SQL Practice track – This series includes 10 comprehensive SQL practice courses to sharpen your skills, perfect for those looking for hands-on practice. Key courses in this track include:
  • SQL Practice Set – Provides a range of exercises across various SQL topics and databases.
  • SQL Practice: A Store – Specifically designed for data analysts, this course offers practical SQL tasks using a database from an online store.
  • SQL Practice: Blog & Traffic Data – Perfect for marketers and data analysts, this course focuses on analyzing traffic data from a pet store blog.
  • SQL Practice Databases – Gathers a variety of datasets for you to practice with. With no guided exercises, you are encouraged to explore the data, formulate your own questions, and find the answers yourself.

You can find many SQL practice materials and premium resources in Your Guide to SQL Practice at LearnSQL.com .

Lastly, we recommend our SQL Basics Cheat Sheet . It is a quick reference guide that covers basic SQL syntax. Keep it handy as you review your SQL knowledge and practice your skills.

Page 1 of SQL Basics Cheat Sheet

Explore 50+ Specific SQL Topic Interview Questions

After you have refreshed your basic SQL knowledge, you might notice certain topics that are trickier for you or more relevant to your specific job role. In this section we've compiled resources that help you prepare for interview questions on specific SQL topics.

JOINs are a fundamental SQL construction used to combine data from multiple tables. They are also an essential topic at any SQL interview.

In our article The Top 10 SQL JOIN Interview Questions with Answers we've gathered the 10 most common questions about SQL JOINs that you might encounter in interviews. For each question we give you a detailed answer that will highlight what the interviewer is looking for in each question.

If you want to practice SQL JOINs, we recommend our interactive SQL JOINs course . It focuses on exercises specifically about SQL JOINs and contains 93 practice exercises to help you get confidence in your joining skills.

Additionally, we recommend Your Complete Guide to SQL JOINs , a comprehensive article that covers the basic knowledge of SQL JOINs, with additional articles and other resources on our platform.

The GROUP BY clause, paired with aggregate functions, is fundamental in SQL for calculating statistics like counts, averages, and sums from your data. This topic is essential for any SQL interview.

Our article Top 9 SQL GROUP BY Interview Questions provides a collection of the most frequently asked interview questions about GROUP BY . Each question includes a detailed answer, making sure you're prepared to discuss these topics during an interview.

If you are looking for an intermediate-level practice of GROUP BY topics, we recommend our Creating Basic SQL Reports course. It offers 100 exercises that focus on nuances of GROUP BY that can be asked about during an interview. It’s a hands-on course where you write your own SQL queries to help you better understand the issues and commit them to memory.

Furthermore, our article GROUP BY and Aggregate Functions: A Complete Overview gives a thorough explanation of GROUP BY and aggregate functions. This comprehensive guide is an excellent resource to round out your study, ensuring you have a robust understanding of how these functions work and how they can be applied in various scenarios.

We know that many of our users work specifically in the domain of data analysis. For these users, we have prepared an article 25 SQL Interview Questions for Data Analysts , which collects common SQL interview questions that can be asked for a role of data analyst. The article covers intermediate and advanced topics, like CTEs or window functions.

Window functions are an advanced SQL topic. Window functions are particularly useful when writing complex reports in SQL. For this reason, they are essential in data analysis and will come up in any data analysis interview.

Our article Top 10 SQL Window Functions Interview Questions contains the most common interview questions you might encounter regarding window functions. Each question has a detailed answer and links to further resources to help you dive deeper into each topic.

For those looking to refresh their knowledge through practice, we recommend our specialized courses:

  • Window Functions – Covers the entire syntax of SQL window functions through interactive, hands-on exercises, making it ideal for those new to window functions or needing a refresher.
  • Window Functions Practice Set - Aimed at those already familiar with window functions, this course provides additional practice to help refine your skills and prepare for more complex interview questions.

Additionally, we recommend our Window Functions Cheat Sheet , a handy quick reference guide for window functions. For a more thorough review, SQL Window Functions Guide is a comprehensive article that covers the basics of window functions with links to additional resources.

Common Table Expressions, or CTEs, is another advanced topic crucial for SQL interviews. CTEs help you organize and manage long and complex queries, make writing complex reports easier, and help you query hierarchical structures through recursive queries.

Our article Top 5 SQL CTE Interview Questions compiles essential CTE-related questions you're likely to face in interviews.in an article. Each question in the article is paired with a detailed answer to help you understand what is the most important in each response.

We also recommend our interactive Recursive Queries course that covers the syntax of CTEs through practice. The course is designed to teach the syntax and use of CTEs, including recursive CTEs, through hands-on exercises.

Finally, check out these articles to help you get ready for an advanced SQL interview:

  • How to Prepare for an Advanced SQL Interview
  • Top 27 Advanced SQL Interview Questions with Answers
  • 15 Tricky SQL Interview Questions for Experienced Users

We also suggest our Advanced SQL Practice track, which is an online series of SQL practice courses designed for advanced users.

In this article we have gathered over 100 SQL interview questions and 20 additional resources compiled here to ensure you're thoroughly prepared. To further enhance your preparation, we recommend our All Forever SQL Package . It provides access to all our current and future courses in a single purchase, making it an excellent investment for your ongoing SQL education and interview readiness.

Sign up for free at LearnSQL.com and explore our SQL courses offer . Each month, we offer one of our courses—typically a practical, hands-on course—for free . This gives you a perfect opportunity to try out our resources without any commitment and see how they can help you succeed in your SQL interview. Take advantage of these offers to boost your confidence and sharpen your SQL skills effectively.

You may also like

programming for problem solving questions

How Do You Write a SELECT Statement in SQL?

programming for problem solving questions

What Is a Foreign Key in SQL?

programming for problem solving questions

Enumerate and Explain All the Basic Elements of an SQL Query

How to think like a programmer — lessons in problem solving

How to think like a programmer — lessons in problem solving

by Richard Reis

aNP21-ICMABUCyfdi4Pys7P0D2wiZqTd3iRY

If you’re interested in programming, you may well have seen this quote before:

“Everyone in this country should learn to program a computer, because it teaches you to think.” — Steve Jobs

You probably also wondered what does it mean, exactly, to think like a programmer? And how do you do it??

Essentially, it’s all about a more effective way for problem solving .

In this post, my goal is to teach you that way.

By the end of it, you’ll know exactly what steps to take to be a better problem-solver.

Why is this important?

Problem solving is the meta-skill.

We all have problems. Big and small. How we deal with them is sometimes, well…pretty random.

Unless you have a system, this is probably how you “solve” problems (which is what I did when I started coding):

  • Try a solution.
  • If that doesn’t work, try another one.
  • If that doesn’t work, repeat step 2 until you luck out.

Look, sometimes you luck out. But that is the worst way to solve problems! And it’s a huge, huge waste of time.

The best way involves a) having a framework and b) practicing it.

“Almost all employers prioritize problem-solving skills first.
Problem-solving skills are almost unanimously the most important qualification that employers look for….more than programming languages proficiency, debugging, and system design.
Demonstrating computational thinking or the ability to break down large, complex problems is just as valuable (if not more so) than the baseline technical skills required for a job.” — Hacker Rank ( 2018 Developer Skills Report )

Have a framework

To find the right framework, I followed the advice in Tim Ferriss’ book on learning, “ The 4-Hour Chef ”.

It led me to interview two really impressive people: C. Jordan Ball (ranked 1st or 2nd out of 65,000+ users on Coderbyte ), and V. Anton Spraul (author of the book “ Think Like a Programmer: An Introduction to Creative Problem Solving ”).

I asked them the same questions, and guess what? Their answers were pretty similar!

Soon, you too will know them.

Sidenote: this doesn’t mean they did everything the same way. Everyone is different. You’ll be different. But if you start with principles we all agree are good, you’ll get a lot further a lot quicker.

“The biggest mistake I see new programmers make is focusing on learning syntax instead of learning how to solve problems.” — V. Anton Spraul

So, what should you do when you encounter a new problem?

Here are the steps:

1. Understand

Know exactly what is being asked. Most hard problems are hard because you don’t understand them (hence why this is the first step).

How to know when you understand a problem? When you can explain it in plain English.

Do you remember being stuck on a problem, you start explaining it, and you instantly see holes in the logic you didn’t see before?

Most programmers know this feeling.

This is why you should write down your problem, doodle a diagram, or tell someone else about it (or thing… some people use a rubber duck ).

“If you can’t explain something in simple terms, you don’t understand it.” — Richard Feynman

Don’t dive right into solving without a plan (and somehow hope you can muddle your way through). Plan your solution!

Nothing can help you if you can’t write down the exact steps.

In programming, this means don’t start hacking straight away. Give your brain time to analyze the problem and process the information.

To get a good plan, answer this question:

“Given input X, what are the steps necessary to return output Y?”

Sidenote: Programmers have a great tool to help them with this… Comments!

Pay attention. This is the most important step of all.

Do not try to solve one big problem. You will cry.

Instead, break it into sub-problems. These sub-problems are much easier to solve.

Then, solve each sub-problem one by one. Begin with the simplest. Simplest means you know the answer (or are closer to that answer).

After that, simplest means this sub-problem being solved doesn’t depend on others being solved.

Once you solved every sub-problem, connect the dots.

Connecting all your “sub-solutions” will give you the solution to the original problem. Congratulations!

This technique is a cornerstone of problem-solving. Remember it (read this step again, if you must).

“If I could teach every beginning programmer one problem-solving skill, it would be the ‘reduce the problem technique.’
For example, suppose you’re a new programmer and you’re asked to write a program that reads ten numbers and figures out which number is the third highest. For a brand-new programmer, that can be a tough assignment, even though it only requires basic programming syntax.
If you’re stuck, you should reduce the problem to something simpler. Instead of the third-highest number, what about finding the highest overall? Still too tough? What about finding the largest of just three numbers? Or the larger of two?
Reduce the problem to the point where you know how to solve it and write the solution. Then expand the problem slightly and rewrite the solution to match, and keep going until you are back where you started.” — V. Anton Spraul

By now, you’re probably sitting there thinking “Hey Richard... That’s cool and all, but what if I’m stuck and can’t even solve a sub-problem??”

First off, take a deep breath. Second, that’s fair.

Don’t worry though, friend. This happens to everyone!

The difference is the best programmers/problem-solvers are more curious about bugs/errors than irritated.

In fact, here are three things to try when facing a whammy:

  • Debug: Go step by step through your solution trying to find where you went wrong. Programmers call this debugging (in fact, this is all a debugger does).
“The art of debugging is figuring out what you really told your program to do rather than what you thought you told it to do.”” — Andrew Singer
  • Reassess: Take a step back. Look at the problem from another perspective. Is there anything that can be abstracted to a more general approach?
“Sometimes we get so lost in the details of a problem that we overlook general principles that would solve the problem at a more general level. […]
The classic example of this, of course, is the summation of a long list of consecutive integers, 1 + 2 + 3 + … + n, which a very young Gauss quickly recognized was simply n(n+1)/2, thus avoiding the effort of having to do the addition.” — C. Jordan Ball

Sidenote: Another way of reassessing is starting anew. Delete everything and begin again with fresh eyes. I’m serious. You’ll be dumbfounded at how effective this is.

  • Research: Ahh, good ol’ Google. You read that right. No matter what problem you have, someone has probably solved it. Find that person/ solution. In fact, do this even if you solved the problem! (You can learn a lot from other people’s solutions).

Caveat: Don’t look for a solution to the big problem. Only look for solutions to sub-problems. Why? Because unless you struggle (even a little bit), you won’t learn anything. If you don’t learn anything, you wasted your time.

Don’t expect to be great after just one week. If you want to be a good problem-solver, solve a lot of problems!

Practice. Practice. Practice. It’ll only be a matter of time before you recognize that “this problem could easily be solved with <insert concept here>.”

How to practice? There are options out the wazoo!

Chess puzzles, math problems, Sudoku, Go, Monopoly, video-games, cryptokitties, bla… bla… bla….

In fact, a common pattern amongst successful people is their habit of practicing “micro problem-solving.” For example, Peter Thiel plays chess, and Elon Musk plays video-games.

“Byron Reeves said ‘If you want to see what business leadership may look like in three to five years, look at what’s happening in online games.’
Fast-forward to today. Elon [Musk], Reid [Hoffman], Mark Zuckerberg and many others say that games have been foundational to their success in building their companies.” — Mary Meeker ( 2017 internet trends report )

Does this mean you should just play video-games? Not at all.

But what are video-games all about? That’s right, problem-solving!

So, what you should do is find an outlet to practice. Something that allows you to solve many micro-problems (ideally, something you enjoy).

For example, I enjoy coding challenges. Every day, I try to solve at least one challenge (usually on Coderbyte ).

Like I said, all problems share similar patterns.

That’s all folks!

Now, you know better what it means to “think like a programmer.”

You also know that problem-solving is an incredible skill to cultivate (the meta-skill).

As if that wasn’t enough, notice how you also know what to do to practice your problem-solving skills!

Phew… Pretty cool right?

Finally, I wish you encounter many problems.

You read that right. At least now you know how to solve them! (also, you’ll learn that with every solution, you improve).

“Just when you think you’ve successfully navigated one obstacle, another emerges. But that’s what keeps life interesting.[…]
Life is a process of breaking through these impediments — a series of fortified lines that we must break through.
Each time, you’ll learn something.
Each time, you’ll develop strength, wisdom, and perspective.
Each time, a little more of the competition falls away. Until all that is left is you: the best version of you.” — Ryan Holiday ( The Obstacle is the Way )

Now, go solve some problems!

And best of luck ?

Special thanks to C. Jordan Ball and V. Anton Spraul . All the good advice here came from them.

Thanks for reading! If you enjoyed it, test how many times can you hit in 5 seconds. It’s great cardio for your fingers AND will help other people see the story.

If this article was helpful, share it .

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

My practical advice for new programmers

Working from home at a laptop

Opensource.com

Have you ever been stuck or gone blank trying to solve a problem related to something that you just learned from YouTube or Google tutorials? You seem to understand every line of the code, but without the tutorial, you find yourself in a difficult position. If you have looked at problem-solving in HackerRank or LeetCode, you can relate to how an aspiring programmer feels seeing those challenges for the first time. Everything seems out of the box! Being unable to apply what you learned from a tutorial might make you doubt your knowledge and abilities as you begin to understand the basics of the programming language you're learning.

Putting programming tutorials into practice

Should you start back at the beginning? If you do that, you may soon find that you've covered those topics more than enough times. Starting from scratch is not necessarily a waste, but how can you be more efficient?

Memorization is simply not the solution in programming. Having said that, you cannot neglect the importance of getting used to syntaxes. There is a significant difference between memorizing and making a habit. The latter is difficult to break. Make a habit of playing around with the programming language's regular syntaxes, functions, methods, patterns, paradigms, and constructs to ace it. Acing a programming language involves a lot of creativity and practice. It is essential to practice syntaxes until they flow as smoothly in your brain as the blood runs through your veins.

How problem-solving works

How you approach solutions depends on many factors. These factors could be anything from technical constraints to user needs. The world has innumerable problems and there are many ways of solving each. Deciding on the best way involves extensive problem-solving skills.

Here is a simple example. You need to achieve a result of 6 by adding two numbers. You can accomplish this several ways:

3+3=6 or 4+2=6 or 5+1=6

Similarly, say you need to achieve a result of 6 by using two numbers and either subtraction, division, or multiplication. You have many options, including:

8-2=6 or 12/2=6 or 3*2=6

Each solution may have a different constraint. You must consider all of these when developing effective real-world solutions. Is the solution feasible? Accessible? Interoperable? Scalable? Minimizing the constraint and developing an optimal solution depends on the business need and type of problem.

Practice matters

The goal of programming is much more than problem-solving. Understanding how the code functions from an engineering perspective is always an advantage. That's where code reviews come into play at an enterprise level. The bare minimum requirement in programming is to have basic coding knowledge, including the language's syntaxes, functions, and methods. At the end of the day, coding is what you do , so practicing always helps improve your skills. Fluency in writing and developing complex solutions comes with consistent practice and learning.

Learning to code

My goal for writing and sharing this article is to encourage new programmers to seek the great problem solver in themselves. Please don't stop believing in yourself.

There are many habits to nurture for successful coding. Here are my ways of staying effective while learning to code:

  • A cheat sheet of syntaxes, methods, and functions can come in handy.
  • Break problems into smaller parts to make them easier to follow.
  • Try to understand the core concept of how code functions.
  • Try to improvise with your solutions but always stick to the basics in the beginning.
  • Create as many applications and components as possible while practicing.
  • Never copy/paste code from open platforms like stack overflow/exchange, especially without understanding the context.
  • After following the tutorial, try to build everything from scratch. If you manage to accomplish half of it by yourself, that's still an achievement.

Good luck to all of us.

Person using a laptop

5 ways to learn C programming on Linux

Download our new eBook for tips and tricks for C programming on Linux and FreeDOS.

Ferris the crab under the sea, unofficial logo for Rust programming language

Why I'm enjoying learning Rust as a Java programmer

Notes from a (budding) Rustacean.

Javascript code close-up with neon graphic overlay

Learn JavaScript by writing a guessing game

Take the first steps toward creating interactive, dynamic web content by practicing some basic JavaScript concepts with a simple game.

Sachin Samal - Web Developer at Christus Health

Related Content

Pair programming

What is AI (artificial intelligence)?

3D robotics hand

Humans and machines: a match made in productivity  heaven. Our species wouldn’t have gotten very far without our mechanized workhorses. From the wheel that revolutionized agriculture to the screw that held together increasingly complex construction projects to the robot-enabled assembly lines of today, machines have made life as we know it possible. And yet, despite their seemingly endless utility, humans have long feared machines—more specifically, the possibility that machines might someday acquire human intelligence  and strike out on their own.

Get to know and directly engage with senior McKinsey experts on AI

Sven Blumberg is a senior partner in McKinsey’s Düsseldorf office; Michael Chui is a partner at the McKinsey Global Institute and is based in the Bay Area office, where Lareina Yee is a senior partner; Kia Javanmardian is a senior partner in the Chicago office, where Alex Singla , the global leader of QuantumBlack, AI by McKinsey, is also a senior partner; Kate Smaje and Alex Sukharevsky are senior partners in the London office.

But we tend to view the possibility of sentient machines with fascination as well as fear. This curiosity has helped turn science fiction into actual science. Twentieth-century theoreticians, like computer scientist and mathematician Alan Turing, envisioned a future where machines could perform functions faster than humans. The work of Turing and others soon made this a reality. Personal calculators became widely available in the 1970s, and by 2016, the US census showed that 89 percent of American households had a computer. Machines— smart machines at that—are now just an ordinary part of our lives and culture.

Those smart machines are also getting faster and more complex. Some computers have now crossed the exascale threshold, meaning they can perform as many calculations in a single second as an individual could in 31,688,765,000 years . And beyond computation, which machines have long been faster at than we have, computers and other devices are now acquiring skills and perception that were once unique to humans and a few other species.

About QuantumBlack, AI by McKinsey

QuantumBlack, McKinsey’s AI arm, helps companies transform using the power of technology, technical expertise, and industry experts. With thousands of practitioners at QuantumBlack (data engineers, data scientists, product managers, designers, and software engineers) and McKinsey (industry and domain experts), we are working to solve the world’s most important AI challenges. QuantumBlack Labs is our center of technology development and client innovation, which has been driving cutting-edge advancements and developments in AI through locations across the globe.

AI is a machine’s ability to perform the cognitive functions we associate with human minds, such as perceiving, reasoning, learning, interacting with the environment, problem-solving, and even exercising creativity. You’ve probably interacted with AI even if you don’t realize it—voice assistants like Siri and Alexa are founded on AI technology, as are some customer service chatbots that pop up to help you navigate websites.

Applied AI —simply, artificial intelligence applied to real-world problems—has serious implications for the business world. By using artificial intelligence, companies have the potential to make business more efficient and profitable. But ultimately, the value of AI isn’t in the systems themselves. Rather, it’s in how companies use these systems to assist humans—and their ability to explain to shareholders and the public what these systems do—in a way that builds trust and confidence.

For more about AI, its history, its future, and how to apply it in business, read on.

Learn more about QuantumBlack, AI by McKinsey .

Circular, white maze filled with white semicircles.

Introducing McKinsey Explainers : Direct answers to complex questions

What is machine learning.

Machine learning is a form of artificial intelligence that can adapt to a wide range of inputs, including large sets of historical data, synthesized data, or human inputs. (Some machine learning algorithms are specialized in training themselves to detect patterns; this is called deep learning. See Exhibit 1.) These algorithms can detect patterns and learn how to make predictions and recommendations by processing data, rather than by receiving explicit programming instruction. Some algorithms can also adapt in response to new data and experiences to improve over time.

The volume and complexity of data that is now being generated, too vast for humans to process and apply efficiently, has increased the potential of machine learning, as well as the need for it. In the years since its widespread deployment, which began in the 1970s, machine learning has had an impact on a number of industries, including achievements in medical-imaging analysis  and high-resolution weather forecasting.

The volume and complexity of data that is now being generated, too vast for humans to process and apply efficiently, has increased the potential of machine learning, as well as the need for it.

What is deep learning?

Deep learning is a more advanced version of machine learning that is particularly adept at processing a wider range of data resources (text as well as unstructured data including images), requires even less human intervention, and can often produce more accurate results than traditional machine learning. Deep learning uses neural networks—based on the ways neurons interact in the human brain —to ingest data and process it through multiple neuron layers that recognize increasingly complex features of the data. For example, an early layer might recognize something as being in a specific shape; building on this knowledge, a later layer might be able to identify the shape as a stop sign. Similar to machine learning, deep learning uses iteration to self-correct and improve its prediction capabilities. For example, once it “learns” what a stop sign looks like, it can recognize a stop sign in a new image.

What is generative AI?

Case study: vistra and the martin lake power plant.

Vistra is a large power producer in the United States, operating plants in 12 states with a capacity to power nearly 20 million homes. Vistra has committed to achieving net-zero emissions by 2050. In support of this goal, as well as to improve overall efficiency, QuantumBlack, AI by McKinsey worked with Vistra to build and deploy an AI-powered heat rate optimizer (HRO) at one of its plants.

“Heat rate” is a measure of the thermal efficiency of the plant; in other words, it’s the amount of fuel required to produce each unit of electricity. To reach the optimal heat rate, plant operators continuously monitor and tune hundreds of variables, such as steam temperatures, pressures, oxygen levels, and fan speeds.

Vistra and a McKinsey team, including data scientists and machine learning engineers, built a multilayered neural network model. The model combed through two years’ worth of data at the plant and learned which combination of factors would attain the most efficient heat rate at any point in time. When the models were accurate to 99 percent or higher and run through a rigorous set of real-world tests, the team converted them into an AI-powered engine that generates recommendations every 30 minutes for operators to improve the plant’s heat rate efficiency. One seasoned operations manager at the company’s plant in Odessa, Texas, said, “There are things that took me 20 years to learn about these power plants. This model learned them in an afternoon.”

Overall, the AI-powered HRO helped Vistra achieve the following:

  • approximately 1.6 million metric tons of carbon abated annually
  • 67 power generators optimized
  • $60 million saved in about a year

Read more about the Vistra story here .

Generative AI (gen AI) is an AI model that generates content in response to a prompt. It’s clear that generative AI tools like ChatGPT and DALL-E (a tool for AI-generated art) have the potential to change how a range of jobs  are performed. Much is still unknown about gen AI’s potential, but there are some questions we can answer—like how gen AI models are built, what kinds of problems they are best suited to solve, and how they fit into the broader category of AI and machine learning.

For more on generative AI and how it stands to affect business and society, check out our Explainer “ What is generative AI? ”

What is the history of AI?

The term “artificial intelligence” was coined in 1956  by computer scientist John McCarthy for a workshop at Dartmouth. But he wasn’t the first to write about the concepts we now describe as AI. Alan Turing introduced the concept of the “ imitation game ” in a 1950 paper. That’s the test of a machine’s ability to exhibit intelligent behavior, now known as the “Turing test.” He believed researchers should focus on areas that don’t require too much sensing and action, things like games and language translation. Research communities dedicated to concepts like computer vision, natural language understanding, and neural networks are, in many cases, several decades old.

MIT physicist Rodney Brooks shared details on the four previous stages of AI:

Symbolic AI (1956). Symbolic AI is also known as classical AI, or even GOFAI (good old-fashioned AI). The key concept here is the use of symbols and logical reasoning to solve problems. For example, we know a German shepherd is a dog , which is a mammal; all mammals are warm-blooded; therefore, a German shepherd should be warm-blooded.

The main problem with symbolic AI is that humans still need to manually encode their knowledge of the world into the symbolic AI system, rather than allowing it to observe and encode relationships on its own. As a result, symbolic AI systems struggle with situations involving real-world complexity. They also lack the ability to learn from large amounts of data.

Symbolic AI was the dominant paradigm of AI research until the late 1980s.

Neural networks (1954, 1969, 1986, 2012). Neural networks are the technology behind the recent explosive growth of gen AI. Loosely modeling the ways neurons interact in the human brain , neural networks ingest data and process it through multiple iterations that learn increasingly complex features of the data. The neural network can then make determinations about the data, learn whether a determination is correct, and use what it has learned to make determinations about new data. For example, once it “learns” what an object looks like, it can recognize the object in a new image.

Neural networks were first proposed in 1943 in an academic paper by neurophysiologist Warren McCulloch and logician Walter Pitts. Decades later, in 1969, two MIT researchers mathematically demonstrated that neural networks could perform only very basic tasks. In 1986, there was another reversal, when computer scientist and cognitive psychologist Geoffrey Hinton and colleagues solved the neural network problem presented by the MIT researchers. In the 1990s, computer scientist Yann LeCun made major advancements in neural networks’ use in computer vision, while Jürgen Schmidhuber advanced the application of recurrent neural networks as used in language processing.

In 2012, Hinton and two of his students highlighted the power of deep learning. They applied Hinton’s algorithm to neural networks with many more layers than was typical, sparking a new focus on deep neural networks. These have been the main AI approaches of recent years.

Traditional robotics (1968). During the first few decades of AI, researchers built robots to advance research. Some robots were mobile, moving around on wheels, while others were fixed, with articulated arms. Robots used the earliest attempts at computer vision to identify and navigate through their environments or to understand the geometry of objects and maneuver them. This could include moving around blocks of various shapes and colors. Most of these robots, just like the ones that have been used in factories for decades, rely on highly controlled environments with thoroughly scripted behaviors that they perform repeatedly. They have not contributed significantly to the advancement of AI itself.

But traditional robotics did have significant impact in one area, through a process called “simultaneous localization and mapping” (SLAM). SLAM algorithms helped contribute to self-driving cars and are used in consumer products like vacuum cleaning robots and quadcopter drones. Today, this work has evolved into behavior-based robotics, also referred to as haptic technology because it responds to human touch.

  • Behavior-based robotics (1985). In the real world, there aren’t always clear instructions for navigation, decision making, or problem-solving. Insects, researchers observed, navigate very well (and are evolutionarily very successful) with few neurons. Behavior-based robotics researchers took inspiration from this, looking for ways robots could solve problems with partial knowledge and conflicting instructions. These behavior-based robots are embedded with neural networks.

Learn more about  QuantumBlack, AI by McKinsey .

What is artificial general intelligence?

The term “artificial general intelligence” (AGI) was coined to describe AI systems that possess capabilities comparable to those of a human . In theory, AGI could someday replicate human-like cognitive abilities including reasoning, problem-solving, perception, learning, and language comprehension. But let’s not get ahead of ourselves: the key word here is “someday.” Most researchers and academics believe we are decades away from realizing AGI; some even predict we won’t see AGI this century, or ever. Rodney Brooks, an MIT roboticist and cofounder of iRobot, doesn’t believe AGI will arrive until the year 2300 .

The timing of AGI’s emergence may be uncertain. But when it does emerge—and it likely will—it’s going to be a very big deal, in every aspect of our lives. Executives should begin working to understand the path to machines achieving human-level intelligence now and making the transition to a more automated world.

For more on AGI, including the four previous attempts at AGI, read our Explainer .

What is narrow AI?

Narrow AI is the application of AI techniques to a specific and well-defined problem, such as chatbots like ChatGPT, algorithms that spot fraud in credit card transactions, and natural-language-processing engines that quickly process thousands of legal documents. Most current AI applications fall into the category of narrow AI. AGI is, by contrast, AI that’s intelligent enough to perform a broad range of tasks.

How is the use of AI expanding?

AI is a big story for all kinds of businesses, but some companies are clearly moving ahead of the pack . Our state of AI in 2022 survey showed that adoption of AI models has more than doubled since 2017—and investment has increased apace. What’s more, the specific areas in which companies see value from AI have evolved, from manufacturing and risk to the following:

  • marketing and sales
  • product and service development
  • strategy and corporate finance

One group of companies is pulling ahead of its competitors. Leaders of these organizations consistently make larger investments in AI, level up their practices to scale faster, and hire and upskill the best AI talent. More specifically, they link AI strategy to business outcomes and “ industrialize ” AI operations by designing modular data architecture that can quickly accommodate new applications.

What are the limitations of AI models? How can these potentially be overcome?

We have yet to see the longtail effect of gen AI models. This means there are some inherent risks involved in using them—both known and unknown.

The outputs gen AI models produce may often sound extremely convincing. This is by design. But sometimes the information they generate is just plain wrong. Worse, sometimes it’s biased (because it’s built on the gender, racial, and other biases of the internet and society more generally).

It can also be manipulated to enable unethical or criminal activity. Since gen AI models burst onto the scene, organizations have become aware of users trying to “jailbreak” the models—that means trying to get them to break their own rules and deliver biased, harmful, misleading, or even illegal content. Gen AI organizations are responding to this threat in two ways: for one thing, they’re collecting feedback from users on inappropriate content. They’re also combing through their databases, identifying prompts that led to inappropriate content, and training the model against these types of generations.

But awareness and even action don’t guarantee that harmful content won’t slip the dragnet. Organizations that rely on gen AI models should be aware of the reputational and legal risks involved in unintentionally publishing biased, offensive, or copyrighted content.

These risks can be mitigated, however, in a few ways. “Whenever you use a model,” says McKinsey partner Marie El Hoyek, “you need to be able to counter biases  and instruct it not to use inappropriate or flawed sources, or things you don’t trust.” How? For one thing, it’s crucial to carefully select the initial data used to train these models to avoid including toxic or biased content. Next, rather than employing an off-the-shelf gen AI model, organizations could consider using smaller, specialized models. Organizations with more resources could also customize a general model based on their own data to fit their needs and minimize biases.

It’s also important to keep a human in the loop (that is, to make sure a real human checks the output of a gen AI model before it is published or used) and avoid using gen AI models for critical decisions, such as those involving significant resources or human welfare.

It can’t be emphasized enough that this is a new field. The landscape of risks and opportunities is likely to continue to change rapidly in the coming years. As gen AI becomes increasingly incorporated into business, society, and our personal lives, we can also expect a new regulatory climate to take shape. As organizations experiment—and create value—with these tools, leaders will do well to keep a finger on the pulse of regulation and risk.

What is the AI Bill of Rights?

The Blueprint for an AI Bill of Rights, prepared by the US government in 2022, provides a framework for how government, technology companies, and citizens can collectively ensure more accountable AI. As AI has become more ubiquitous, concerns have surfaced  about a potential lack of transparency surrounding the functioning of gen AI systems, the data used to train them, issues of bias and fairness, potential intellectual property infringements, privacy violations, and more. The Blueprint comprises five principles that the White House says should “guide the design, use, and deployment of automated systems to protect [users] in the age of artificial intelligence.” They are as follows:

  • The right to safe and effective systems. Systems should undergo predeployment testing, risk identification and mitigation, and ongoing monitoring to demonstrate that they are adhering to their intended use.
  • Protections against discrimination by algorithms. Algorithmic discrimination is when automated systems contribute to unjustified different treatment of people based on their race, color, ethnicity, sex, religion, age, and more.
  • Protections against abusive data practices, via built-in safeguards. Users should also have agency over how their data is used.
  • The right to know that an automated system is being used, and a clear explanation of how and why it contributes to outcomes that affect the user.
  • The right to opt out, and access to a human who can quickly consider and fix problems.

At present, more than 60 countries or blocs have national strategies governing the responsible use of AI (Exhibit 2). These include Brazil, China, the European Union, Singapore, South Korea, and the United States. The approaches taken vary from guidelines-based approaches, such as the Blueprint for an AI Bill of Rights in the United States, to comprehensive AI regulations that align with existing data protection and cybersecurity regulations, such as the EU’s AI Act, due in 2024.

There are also collaborative efforts between countries to set out standards for AI use. The US–EU Trade and Technology Council is working toward greater alignment between Europe and the United States. The Global Partnership on Artificial Intelligence, formed in 2020, has 29 members including Brazil, Canada, Japan, the United States, and several European countries.

Even though AI regulations are still being developed, organizations should act now to avoid legal, reputational, organizational, and financial risks. In an environment of public concern, a misstep could be costly. Here are four no-regrets, preemptive actions organizations can implement today:

  • Transparency. Create an inventory of models, classifying them in accordance with regulation, and record all usage across the organization that is clear to those inside and outside the organization.
  • Governance. Implement a governance structure for AI and gen AI that ensures sufficient oversight, authority, and accountability both within the organization and with third parties and regulators.
  • Data management. Proper data management includes awareness of data sources, data classification, data quality and lineage, intellectual property, and privacy management.
  • Model management. Organizations should establish principles and guardrails for AI development and use them to ensure all AI models uphold fairness and bias controls.
  • Cybersecurity and technology management. Establish strong cybersecurity and technology to ensure a secure environment where unauthorized access or misuse is prevented.
  • Individual rights. Make users aware when they are interacting with an AI system, and provide clear instructions for use.

How can organizations scale up their AI efforts from ad hoc projects to full integration?

Most organizations are dipping a toe into the AI pool—not cannonballing. Slow progress toward widespread adoption is likely due to cultural and organizational barriers. But leaders who effectively break down these barriers will be best placed to capture the opportunities of the AI era. And—crucially—companies that can’t take full advantage of AI are already being sidelined by those that can, in industries like auto manufacturing and financial services.

To scale up AI, organizations can make three major shifts :

  • Move from siloed work to interdisciplinary collaboration. AI projects shouldn’t be limited to discrete pockets of organizations. Rather, AI has the biggest impact when it’s employed by cross-functional teams with a mix of skills and perspectives, enabling AI to address broad business priorities.
  • Empower frontline data-based decision making . AI has the potential to enable faster, better decisions at all levels of an organization. But for this to work, people at all levels need to trust the algorithms’ suggestions and feel empowered to make decisions. (Equally, people should be able to override the algorithm or make suggestions for improvement when necessary.)
  • Adopt and bolster an agile mindset. The agile test-and-learn mindset will help reframe mistakes as sources of discovery, allaying the fear of failure and speeding up development.

Learn more about QuantumBlack, AI by McKinsey , and check out AI-related job opportunities if you’re interested in working at McKinsey.

Articles referenced:

  • “ As gen AI advances, regulators—and risk functions—rush to keep pace ,” December 21, 2023, Andreas Kremer, Angela Luget , Daniel Mikkelsen , Henning Soller , Malin Strandell-Jansson, and Sheila Zingg
  • “ What is generative AI? ,” January 19, 2023
  • “ Tech highlights from 2022—in eight charts ,” December 22, 2022
  • “ Generative AI is here: How tools like ChatGPT could change your business ,” December 20, 2022, Michael Chui , Roger Roberts , and Lareina Yee  
  • “ The state of AI in 2022—and a half decade in review ,” December 6, 2022, Michael Chui , Bryce Hall , Helen Mayhew , Alex Singla , and Alex Sukharevsky  
  • “ Why businesses need explainable AI—and how to deliver it ,” September 29, 2022, Liz Grennan , Andreas Kremer, Alex Singla , and Peter Zipparo
  • “ Why digital trust truly matters ,” September 12, 2022, Jim Boehm , Liz Grennan , Alex Singla , and Kate Smaje
  • “ McKinsey Technology Trends Outlook 2023 ,” July 20, 2023, Michael Chui , Mena Issler, Roger Roberts , and Lareina Yee  
  • “ An AI power play: Fueling the next wave of innovation in the energy sector ,” May 12, 2022, Barry Boswell, Sean Buckley, Ben Elliott, Matias Melero , and Micah Smith  
  • “ Scaling AI like a tech native: The CEO’s role ,” October 13, 2021, Jacomo Corbo, David Harvey, Nicolas Hohn, Kia Javanmardian , and Nayur Khan
  • “ What the draft European Union AI regulations mean for business ,” August 10, 2021, Misha Benjamin, Kevin Buehler , Rachel Dooley, and Peter Zipparo
  • “ Winning with AI is a state of mind ,” April 30, 2021, Thomas Meakin , Jeremy Palmer, Valentina Sartori , and Jamie Vickers
  • “ Breaking through data-architecture gridlock to scale AI ,” January 26, 2021, Sven Blumberg , Jorge Machado , Henning Soller , and Asin Tavakoli  
  • “ An executive’s guide to AI ,” November 17, 2020, Michael Chui , Brian McCarthy, and Vishnu Kamalnath
  • “ Executive’s guide to developing AI at scale ,” October 28, 2020, Nayur Khan , Brian McCarthy, and Adi Pradhan
  • “ An executive primer on artificial general intelligence ,” April 29, 2020, Federico Berruti , Pieter Nel, and Rob Whiteman
  • “ The analytics academy: Bridging the gap between human and artificial intelligence ,” McKinsey Quarterly , September 25, 2019, Solly Brown, Darshit Gandhi, Louise Herring , and Ankur Puri  

This article was updated in April 2024; it was originally published in April 2023.

3D robotics hand

Want to know more about AI?

Related articles.

Abstract light explosion render. Beams of light shooting free from center of mass. - stock photo

Ten unsung digital and AI ideas shaping business

Complex Digital Structure Growing Endlessly - Intricate Connection Lines Symbolizing Innovative Artificial Intelligence Or Big Data Models

Driving innovation with generative AI

Video of colorful hexagons overlapping with shifting light.

As gen AI advances, regulators—and risk functions—rush to keep pace

  • Trending Now
  • Foundational Courses
  • Data Science
  • Practice Problem
  • Machine Learning
  • System Design
  • DevOps Tutorial

Welcome to the daily solving of our PROBLEM OF THE DAY with Saurabh Bansal. We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of Arrays but also build up problem-solving skills. You have given two sorted arrays arr1[] & arr2[] of distinct elements. The first array has one element extra added in between. Return the index of the extra element.

Note : 0-based indexing is followed.

Input: n = 7, arr1[] = {2,4,6,8,9,10,12}, arr2[] = {2,4,6,8,10,12} Output: 4 Explanation: In the first array, 9 is extra added and it's index is 4.

Give the problem a try before going through the video. All the best!!! Problem Link: https://practice.geeksforgeeks.org/problems/index-of-an-extra-element/1

Video Thumbnail

COMMENTS

  1. Problems

    Boost your coding interview skills and confidence by practicing real interview questions with LeetCode. Our platform offers a range of essential problems for practice, as well as the latest questions being asked by top-tier companies. ... Interview. Store Study Plan. See all. Array 1653. String 700. Hash Table 599. Dynamic Programming 501. Math ...

  2. Online Coding Practice Problems & Challenges

    Recommended Practice Topics. Practice over 5000+ problems in coding languages like Python, Java, JavaScript, C++, SQL and HTML. Start with beginner friendly problems and solve hard problems as you become better.

  3. Basic Programming Problems

    Learn Programming - How To Code. In the world of programming, mastering the fundamentals is key to becoming a proficient developer.In this article, we will explore a variety of basic programming problems that are essential for every aspiring coder to understand. By delving into these foundational challenges, you will gain valuable insights into problem-solving techniques and build a strong ...

  4. How to Solve Coding Problems with a Simple Four Step Method

    In this post, we've gone over the four-step problem-solving strategy for solving coding problems. Let's review them here: Step 1: understand the problem. Step 2: create a step-by-step plan for how you'll solve it. Step 3: carry out the plan and write the actual code.

  5. Programming tutorials, Coding problems, and Practice questions

    Functional Programming. Higher Order Functions and Decorators. Practice programming skills with tutorials and practice problems of Basic Programming, Data Structures, Algorithms, Math, Machine Learning, Python. HackerEarth is a global hub of 5M+ developers.

  6. The 10 Most Popular Coding Challenge Websites [Updated for 2021]

    A great way to improve your skills when learning to code is by solving coding challenges. Solving different types of challenges and puzzles can help you become a better problem solver, learn the intricacies of a programming language, prepare for job interviews, learn new algorithms, and more.

  7. C Exercises

    Q2: Write a Program to find the Sum of two numbers entered by the user. In this problem, you have to write a program that adds two numbers and prints their sum on the console screen. For Example, Input: Enter two numbers A and B : 5 2. Output: Sum of A and B is: 7.

  8. Practice

    Easy 415K 31.49%. Platform to practice programming problems. Solve company interview questions and improve your coding intellect.

  9. Programming Problems and Competitions :: HackerRank

    Problem Solving (Basic) Problem Solving (Intermediate) +1. Join over 23 million developers in solving code challenges on HackerRank, one of the best ways to prepare for programming interviews.

  10. 20 Code Challenges To Put What You're Learning to the Test

    These challenges are good for practicing your skills at using a programming language. Build a binary search tree. Write a program that prints the numbers from 1 to 100. But for multiples of three, print Fizz instead of the number, and multiples of five, print Buzz. For numbers that are multiples of both three and five, print FizzBuzz.

  11. 75 Basic Programming Problems and Tutorials for Practice

    Basic Programming Problems: Engaging in code challenges offers many benefits, serving as a dynamic tool to enhance problem-solving proficiency, deepen your comprehension of the programming language you work with, and acquaint yourself with diverse algorithms. If you aspire to elevate your programming skills, immersing yourself in coding is the most effective avenue.

  12. 15 Common Problem-Solving Interview Questions

    Here are a few examples of technical problem-solving questions: 1. Mini-Max Sum. This well-known challenge, which asks the interviewee to find the maximum and minimum sum among an array of given numbers, is based on a basic but important programming concept called sorting, as well as integer overflow.

  13. 100+ Coding Interview Questions for Programmers and ...

    Top 100 Coding Problems from Programming Job interviews. Without wasting any more of your time, here is my list of 100 frequently asked coding problems from programming job interviews. In order to get most of this list, I suggest actually solving the problem. Do it yourself, no matter whether you are stuck because that's the only way to learn.

  14. 40 Coding Challenges (SOLVED with CODE) To Kill Your Next Coding

    Strings 25. Heaps and Maps 12. Sorting 26. You may hate code challenges and coding interviews but reality is a lot of companies from Google to Amazon do care that you understand the difference between O(n log n) and O(n²), that you do understand when different data structures are appropriate, and that you can leverage these (very basic) skills ...

  15. 10 Common Coding Interview Problems [Solved]

    We just published a course on the freeCodeCamp.org YouTube channel that will teach you how to solve 10 common coding problems and improve your problem-solving skills. This course was developed Inside code. He is an experienced developer and has a good understanding of the types of coding challenges often used in programmer interviews.

  16. Solve C

    Join over 23 million developers in solving code challenges on HackerRank, one of the best ways to prepare for programming interviews.

  17. C programming Exercises, Practice, Solution

    C is a general-purpose, imperative computer programming language, supporting structured programming, lexical variable scope and recursion, while a static type system prevents many unintended operations. C was originally developed by Dennis Ritchie between 1969 and 1973 at Bell Labs.

  18. Top 20 Algorithms Coding Problems for Programming Interviews with

    If you need more such coding questions, you can take help from books like Cracking The Code Interview by Gayle Laakmann McDowell which contains 189+ Programming questions and solutions. A good ...

  19. Python Exercise with Practice Questions and Solutions

    The best way to learn is by practising it more and more. The best thing about this Python practice exercise is that it helps you learn Python using sets of detailed programming questions from basic to advanced. It covers questions on core Python concepts as well as applications of Python in various domains.

  20. Programming Problem-Solving Interview Questions You Should Ask

    During the technical interview process, we ask candidates to answer a simple programming problem-solving question which has multiple solutions with different simplicity/scalability trade-offs (e.g. compute prefix sums of a sequence of numbers). We assess whether a candidate notices the scalability aspect and whether he/she can deliver the ...

  21. 45 Common Coding Interview Questions

    P: Plan your approach and solution. I: Implement your solution. R: Review your solution. E: Evaluate your solution. To prepare for a whiteboard challenge, "practice talking through your problem-solving process ," says Archie Payne, president of CalTek Staffing, an IT and technical staffing firm.

  22. Top 40 Coding Interview Questions You Should Know

    Encapsulation - A concept that refers to the wrapping of code and data together into a single unit. This is one of the very common coding interview questions, that often allows the interviewer to branch out into related topics based on the candidate's answers. 12. Explain what a Binary Search Tree is.

  23. Top 100+ SQL Interview Questions and Practice Exercises

    Practice solving similar problems under timed conditions. Whiteboard Interviews: Be ready to write code in pseudocode and discuss your thought process. Focus on explaining the concepts and logic behind your solutions more than the exact syntax, which demonstrates a deeper understanding of the problem-solving process. Additional Tips

  24. Introduction to IT Problem Solving: Programming Fundamentals

    Using a Graphical User Interface • Previously for output, we have been using System.out.println to print to the IDE or a console window • Users are now used to seeing graphical interfaces instead of just a text-based command prompt • For now, don't worry about the details • Pay attention to the format of the code IT 106: Introduction to IT Problem Solving Using Computer Programming

  25. How to think like a programmer

    Simplest means you know the answer (or are closer to that answer). After that, simplest means this sub-problem being solved doesn't depend on others being solved. Once you solved every sub-problem, connect the dots. Connecting all your "sub-solutions" will give you the solution to the original problem. Congratulations!

  26. My practical advice for new programmers

    The goal of programming is much more than problem-solving. Understanding how the code functions from an engineering perspective is always an advantage. That's where code reviews come into play at an enterprise level. The bare minimum requirement in programming is to have basic coding knowledge, including the language's syntaxes, functions, and ...

  27. 7 Problem-Solving Skills That Can Help You Be a More ...

    What is problem-solving? Problem-solving is both an ability and a process. As an ability, problem-solving can aid in resolving issues faced in different environments like home, school, abroad, and social situations, among others. As a process, problem-solving involves a series of steps for finding solutions to questions or concerns that arise ...

  28. What is AI (artificial intelligence)?

    QuantumBlack, McKinsey's AI arm, helps companies transform using the power of technology, technical expertise, and industry experts. With thousands of practitioners at QuantumBlack (data engineers, data scientists, product managers, designers, and software engineers) and McKinsey (industry and domain experts), we are working to solve the world's most important AI challenges.

  29. PROBLEM OF THE DAY : 08/06/2024

    Welcome to the daily solving of our PROBLEM OF THE DAY with Saurabh Bansal. We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of Arrays but also build up problem-solving skills. You have given two sorted arrays arr1[] & arr2[] of distinct elements. The first array has one element extra added ...