Open In App

How to use Chat-GPT to solve Coding Problems?

Last Updated : 27 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Its 2023 and AI Models are on the rise, even for a simple task. Then why not use it for solving Coding problems? One such popular model is Chat-GPT. Chat-GPT can be a valuable resource for students looking to solve coding-related problems. It can provide quick answers to simple questions about syntax, algorithms, and data structures, which can save students time and help them better understand programming concepts. Chat-GPT can also assist students with more complex coding problems by suggesting potential solutions, providing examples, or explaining coding concepts in a clear and concise way.

By using Chat-GPT, students can learn at their own pace and in a format that suits their learning style. They can ask questions and receive answers immediately, without having to wait for a teacher or tutor to become available.

How to use Chat-GPT to solve Coding Problems?

How to use Chat-GPT to solve Coding Problems?

How to use Chat-GPT efficiently to solve Coding Problems?

Chat-GPT is Phenomenal when it comes to problem-solving. Students can ask Chat-GPT-specific questions related to coding and programming, and it can provide step-by-step guidance on how to solve coding problems. Additionally, Chat-GPT can offer coding tips, tricks, and best practices, helping students to improve their coding skills and knowledge. With its vast knowledge base and ability to quickly process and analyze data, Chat-GPT is a valuable resource for students seeking coding help.

All of us know about the capabilities of Chat-GPT. Solving coding and Data Structure’s related problems is one of the major capabilities of Chat GPT. This ability of Chat GPT is very helpful for coders and debuggers around the world as Chat GPT helps in solving coding problems.

Note: If you are a beginner or New to programming then, first you should focus on your fundamentals and roots of programming then start solving problems on your own. But if you are stuck badly in any problem and you’re not able to find the exact answer or stuck in any edge-case or corner case then you can go for Chat GPT.

Using text-based AI models like Chat-GPT can be a bit tricky if you are new to it. To help you with this, we have compiled a list of pointers to look for while using Chat-GPT to solve Coding Problems:

1. Be specific 

When asking a coding question, be as specific as possible. Provide details on what you’re trying to accomplish, what code you’ve already written, what error messages you’re getting, and what you’ve tried so far. The more specific you are, the more helpful the response from Chat-GPT will be.

2. Use proper keywords

Use proper coding terminology when asking your question. This will help Chat-GPT better understand your question and provide more accurate responses.

3. Break down your problem into smaller parts

If you’re struggling with a larger coding problem, try breaking it down into smaller parts. This can make the problem easier to solve, and it can help Chat-GPT better understand what you’re trying to accomplish.

4. Provide examples

Providing examples of your code or the output you’re expecting can help Chat-GPT better understand your problem and provide more accurate responses.

5. Check the Chat-GPT response

Once Chat-GPT responds to your question, read the response carefully and make sure you understand it. If you don’t understand the response, try rephrasing your question or providing more details.

6. Experiment and Improvise

Use Chat-GPT’s responses to experiment with different solutions to your coding problem. Try out different code snippets or approaches and see what works best.

How to form Query correctly to get Expected Answer From Chat-GPT?

It’s observed that If one does not mention the clear Problem statement and all other required data-set which is required to solve the problem statement then Chat-GPT may give the wrong answer as Output.

There should be a plan to search the problem statement in Chat GPT:

  • Define the problem: Make sure you understand what the problem is asking you to do. Break down the problem into smaller parts if necessary.
  • Plan a solution: Once you have understood the problem, plan a solution before starting to code. Think about the data structures and algorithms that could be used to solve the problem.
  • Write the code: Implement your plan in code. Use a programming language that you are comfortable with.
  • Test your code: Test your code with different inputs and make sure it is giving correct outputs.
  • Refine your solution: If your code is not working correctly, refine your solution and try again.

How to use Chat-GPT to solve different types of Coding Problems?

1. Data Structure and Algorithm (DSA) Related Problems

Suppose, we want Chat GPT to solve the Tower-Of-Hanoi problem then we’ll follow the following steps:

STEP 1: Provide the Clear & Crisp Problem Statement so that it’s easier for the AI to understand the problem and there should be no scope of confusion here.

Example: Tower of Hanoi is a mathematical puzzle where we have three rods (A, B, and C) and N disks. Initially, all the disks are stacked in decreasing value of diameter i.e., the smallest disk is placed on the top and they are on rod A. The objective of the puzzle is to move the entire stack to another rod (here considered C), obeying the following simple rules: 

  • Only one disk can be moved at a time.
  • Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack. 
  • No disk may be placed on top of a smaller disk.

STEP 2: Provide Input/Output Examples with Output explanation:

Input: 2
Output: Disk 1 moved from A to B
Disk 2 moved from A to C
Disk 1 moved from B to C

STEP 3: State the Required Result. Ask Chat-GPT to provide the result in the format you want.

Example: Solve this problem using recursion provides its explanation, algorithmic steps, C++ Code Implementation, and Complexity analysis.

STEP 4: Now, Chat-GPT will generate the required answer.

Generated Content:

Chat-GPT 4

So, this is how we can solve problem statements using Chat-GPT as we can see:

  • We got an explanation of the problem statement
  • Then, algorithmic steps to solve the problem
  • C++ Implementation
  • Complexity Analysis

Don’t worry, we have already tested Chat-GPT’s response for Tower of Hanoi problem with sample test cases here.

2. Solving Complexity Analysis for Algorithms Using Chat-GPT

Suppose, we want Chat-GPT to compute the Complexity of any algorithm, then we’ll follow the following steps:

STEP 1: Provide a clear and crisp problem statement so that it’s easier for the AI to understand the problem and there should be no scope of confusion here.

Example: 

Provide the complexity analysis of the below code with Time complexity and Auxiliary Stack Space.

The given code is of Fibonacci problem using Recursion.

C++




#include <bits/stdc++.h>
using namespace std;
  
int fib(int n)
  
{
    if (n == 0)
        return 0;
    if (n == 1 || n == 2)
        return 1;
    else
        return (fib(n - 1) + fib(n - 2));
}
  
int main()
{
    int n = 5;
    cout << "Fibonacci series of 5 numbers is: ";
    for (int i = 0; i < n; i++)
    {
        cout << fib(i) << " ";
    }
    return 0;
}


 STEP 2:  Fetch the results

Solving Complexity Analysis for Algorithms Using Chat-GPT

Solving Complexity Analysis for Algorithms Using Chat-GPT

Expected Answer: 

  • Time Complexity: O(2n), 
  • Auxiliary Space: O(n)

Generated Answer: The given code computes the first n numbers of the Fibonacci series using recursion.

  • The time complexity of the fib() function can be computed using a recursive tree. Each node in the tree represents a recursive call to the fib() function. At each level of the tree, the number of nodes is twice the number of nodes at the previous level. Therefore, the height of the tree is n. The work done at each node is constant time, i.e., O(1).
    Therefore, the time complexity of the fib() function is O(2n).
  • The main() function calls the fib() function n times in the for loop. Since the time complexity of the fib() function is O(2^n), the time complexity of the main() function is O(n * 2n).
    The space complexity of the program is O(n) because the maximum number of function calls that can be present in the call stack at any point in time is n.

3. Converting/Translating Language of the Algorithm/Code Using Chat-GPT

Suppose, we want Chat-GPT to change the Language of the code then we’ll follow the following steps:

STEP 1:  Provide the Clear & Crisp Problem Statement so that it’s easier for the AI to understand the problem and there should be no scope of confusion here.

If we want to change the programming language of any Code then we can simply command Chat-GPT to do the needful.

Example: Convert the below code into Java

C++




#include <bits/stdc++.h>
using namespace std;
  
int fib(int n)
{
    if (n == 0)
        return 0;
    if (n == 1 || n == 2)
        return 1;
    else
        return (fib(n - 1) + fib(n - 2));
}
  
int main()
{
    int n = 5;
    cout << "Fibonacci series of 5 numbers is: ";
    for (int i = 0; i < n; i++)
    {
        cout << fib(i) << " ";
    }
    return 0;
}


STEP 2: Generating the results

Converting/Translating Language of the Algorithm/Code Using Chat-GPT

Converting/Translating Language of the Algorithm/Code Using Chat-GPT

Below is the Generated Code:

Java




import java.util.*;
  
public class Fibonacci {
  
    public static int fib(int n) {
        if (n == 0)
            return 0;
        if (n == 1 || n == 2)
            return 1;
        else
            return (fib(n - 1) + fib(n - 2));
    }
  
    public static void main(String[] args) {
        int n = 5;
        System.out.print("Fibonacci series of 5 numbers is: ");
        for (int i = 0; i < n; i++) {
            System.out.print(fib(i) + " ");
        }
    }
}


Output

Fibonacci series of 5 numbers is: 0 1 1 2 3 

4. Creating JavaScript Functionalities for Development & Projects

Suppose, we want Chat-GPT to make any JavaScript functionality that can display Increment and Decrements in the browsers then we’ll follow the following steps:

STEP 1: Provide the Clear & Crisp Problem Statement so that it’s easier for the AI to understand the problem and there should be no scope of confusion here.

Example: Create a JavaScript program that enables user to increment and decrement a value by one by clicking increment and decrement separately

STEP 2: Fetching the Results:

Creating JavaScript Functionalities for Development & Projects

Creating JavaScript Functionalities for Development & Projects

As we can see that Chat-GPT has given us the generated code as HTML file.

Output: Sure! Here’s a simple JavaScript program that allows a user to increment and decrement a value by one by clicking on separate buttons:

HTML




<!DOCTYPE html>
  
<html>
<head>
  
    <title>Increment and Decrement</title>
  
  </head>
<body>
  
 <h1>Increment and Decrement</h1>
 <p>Current Value: <span id="value">0</span></p>
<button id="increment">Increment</button>
<button id="decrement">Decrement</button>
  
  </body>
</html>


Javascript




<script>
 const valueElem = document.getElementById("value");
const incrementButton = document.getElementById("increment");
const decrementButton = document.getElementById("decrement");
  
 let value = 0;
  
 function updateValue() {
 valueElem.textContent = value;
  }  
  
      function incrementValue() {
  value += 1;
updateValue();
  
      }
  
  function decrementValue() {
  
        value -= 1;
       updateValue();
 }
  
  incrementButton.addEventListener("click", incrementValue);
 decrementButton.addEventListener("click", decrementValue);
  
 </script>


STEP 3:  Testing the Generated Code

  • Open any IDE (eg., Virtual Studio Code)
  • Then, Create an index.html file.
  • copy & paste the generated code
  • Run with live server

Chat-GPT 3

As we can see that the code is working fine and we have 4 Components in the display:

1. Heading showing “Increment and Decrement”.
2. Paragraph tag with span value will show the Increment/Decrement values, Initially the value is 0.
3. Button to increment values
4. Another Button to decrement values.

How NOT to Use Chat-GPT for Solving Coding Problems

We have to be careful while solving coding-related problems using Chat-GPT because Chat-GPT does not claim 100% Accuracy for Generated Output. Suppose we are given a Problem Statement in Story Format / In-Sufficient Data / Wrong Examples / Wrong I/O. In That Case, Chat-GPT will surely Generate the Wrong Answer for an Input.

Case 1: Not providing sufficient information to generate the desired output

Let’s take an example of a popular problem Print Spiral Matrix. The task is to print a spiral matrix but in Anti-Clock-Wise Direction. So let’s give Chat-GPT a command to Print the Spiral Matrix in Anti-Clock Wise Direction.

Query asked: 

Given an m x n matrix, return all elements of the matrix in spiral order in an anticlockwise direction. Input: matrix = [[1,2,3],[4,5,6],[7,8,9]].

Answer generated by Chat-GPT:

Answer generated by Chat-GPT for Not providing sufficient information to generate the desired output

Answer generated by Chat-GPT for Not providing sufficient information to generate the desired output

Now let’s try to run the generated C++ code against the above input with the expected output as [1 4 7 8 9 6 5 2 3]

C++




#include <iostream>
#include <vector>
  
using namespace std;
  
vector<int> AntispiralOrder(vector<vector<int>>& matrix) {
    int top = 0, bottom = matrix.size() - 1, left = 0, right = matrix[0].size() - 1;
    int dir = 1;
    vector<int> result;
  
    while (top <= bottom && left <= right) {
        if (dir == 1) {
            for (int i = left; i <= right; i++) {
                result.push_back(matrix[top][i]);
            }
            top++;
  
            for (int i = top; i <= bottom; i++) {
                result.push_back(matrix[i][right]);
            }
            right--;
  
            for (int i = right; i >= left; i--) {
                result.push_back(matrix[bottom][i]);
            }
            bottom--;
  
            for (int i = bottom; i >= top; i--) {
                result.push_back(matrix[i][left]);
            }
            left++;
        }
        dir *= -1;
    }
  
    return result;
}
  
int main() {
    vector<vector<int>> matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
  
    vector<int> result = AntispiralOrder(matrix);
  
    for (int i = 0; i < result.size(); i++) {
        cout << result[i] << " "; //1 4 7 8 9 6 5 2 3
    }
  
    return 0;
}


Output

1 2 3 6 9 8 7 4 5 

Expected Output

1 4 7 8 9 6 5 2 3

As we can see that we are getting the wrong answer for the above Inputs.

Why Chat-GPT is producing incorrect output in this case?

We have provided insufficient Information this is the main reason Why Chat-GPT is giving us the wrong Output:

Let’s see what should be the proper format for the above Example to get the expected answer:

Write a program to print a spiral matrix in an anticlockwise direction.
Command: Example: Input: arr = [[1,2,3],[4,5,6],[7,8,9]]; Output: arr = [1,4,7,8,9,6,3,2,5]

Generated Code:

C++




#include <iostream>
#include <vector>
  
using namespace std;
  
vector<int> spiralOrder(vector<vector<int>>& matrix) {
    vector<int> res;
    if (matrix.empty()) {
        return res;
    }
    int m = matrix.size();
    int n = matrix[0].size();
    int i = 0, j = n-1;
    while (i < j && i <= m-i-1 && j >= n-j && j <= j-i) {
        for (int k = i; k <= m-i-1; k++) {
            res.push_back(matrix[k][i]);
        }
        for (int k = i+1; k <= j; k++) {
            res.push_back(matrix[m-i-1][k]);
        }
        if (i < j && i <= m-i-2 && j >= n-j) {
            for (int k = m-i-2; k >= i; k--) {
                res.push_back(matrix[k][j]);
            }
        }
        if (i < j && i <= m-i-1 && j >= n-j+1) {
            for (int k = j-1; k >= i+1; k--) {
                res.push_back(matrix[i][k]);
            }
        }
        i++;
        j--;
    }
    if (i == j) {
        res.push_back(matrix[i][i]);
    }
    return res;
}
  
int main() {
    vector<vector<int>> arr = {{1,2,3},{4,5,6},{7,8,9}};
    vector<int> res = spiralOrder(arr);
    for (int i = 0; i < res.size(); i++) {
        cout << res[i] << " ";
    }
    cout << endl;
    return 0;
}


Output

1 4 7 8 9 6 3 2 5 

As we can see that we are getting the Correct answers for the above Inputs.

Case 2: Chat-GPT is still new and learning

Though Chat-GPT is able to produce almost every answer and even correct it to most extent, still it is very new and learning. So there might be cases where it shows you incorrect answers, or fail to give you the correct answer the first time. 

For example, 

Here’s how Chat-GPT failed to provide complexity analysis for Fibonacci Number Recursion approach the first time.

how Chat-GPT failed to provide complexity analysis for Fibonacci Number Recursion approach the first time

how Chat-GPT failed to provide complexity analysis for Fibonacci Number Recursion approach the first time

But gave the correct output the second time.

how Chat-GPT gave the correct output the second time

how Chat-GPT gave the correct output the second time

Why can’t you trust Chat-GPT to generate the correct output every time?

Chat-GPT is designed to generate responses based on the patterns and relationships it has learned from large amounts of text data. While it can generate impressive and often highly accurate responses, it is not perfect and can still make errors or generate responses that are inappropriate or irrelevant.

One reason for this is that Chat-GPT lacks the ability to truly understand the context and the nuances of language in the same way that humans do. It may not be able to discern sarcasm, humor, or other subtle cues that can greatly affect the meaning of a message.

Example:

We want to convert the language of any code, Let’s say a C++ program to JavaScript:

Here is the C++ Code which we want chat-GPT to convert into JavaScript:

C++




#include <bits/stdc++.h>
using namespace std;
#define int long long
  
// Function to find Number of subarrays
// which are repetition of same array
// twice on swapping any number
// of elements
int noOfSubarrays(int N, int A[])
{
  
    // Initializing "mp" and "cnt"
    map<vector<int>, int> mp;
    vector<int> cnt(10, 0);
    mp[cnt]++;
  
    // Iterating through the array and
    // updating "mp" and "cnt"
    for (int i = 0; i < N; i++) {
        cnt[A[i]]++;
        cnt[A[i]] %= 2;
        mp[cnt]++;
    }
  
    // Initialize a variable "ans"
    // to store the answer
    int ans = 0;
  
    // Iterating through the map and
    // accordingly updating the "ans"
    for (auto it : mp) {
        int temp = it.second;
        ans += (temp * (temp - 1)) / 2;
    }
  
    // Return final answer
    return ans;
}
  
// Driver's code
int32_t main()
{
    int N = 8;
    int A[] = { 2, 0, 2, 3, 0, 3, 2, 2 };
  
    int answer = noOfSubarrays(N, A);
  
    // Function Call
    cout << answer << endl;
  
    return 0;
}


Output

4

Command: Convert the below C++ code into JavaScript

Expected Output: 4

Generated Output: 

 

Below is the generated code:

Javascript




// Function to find Number of subarrays
// which are repetition of same array
// twice on swapping any number
// of elements
function noOfSubarrays(N, A) {
  
  // Initializing "mp" and "cnt"
  let mp = new Map();
  let cnt = new Array(10).fill(0);
  mp.set(cnt, 1);
  
  // Iterating through the array and
  // updating "mp" and "cnt"
  for (let i = 0; i < N; i++) {
    cnt[A[i]]++;
    cnt[A[i]] %= 2;
    mp.set(cnt, (mp.get(cnt) || 0) + 1);
  }
  
  // Initialize a variable "ans"
  // to store the answer
  let ans = 0;
  
  // Iterating through the map and
  // accordingly updating the "ans"
  for (let temp of mp.values()) {
    ans += (temp * (temp - 1)) / 2;
  }
  
  // Return final answer
  return ans;
}
  
// Driver's code
let N = 8;
let A = [2, 0, 2, 3, 0, 3, 2, 2];
  
let answer = noOfSubarrays(N, A);
  
// Function Call
console.log(answer);


Output

36

As we can see that Chat-GPT is giving wrong answer after compiling and testing the generated Javascript code.

Additionally, Chat-GPT is only as reliable as the data it has been trained on. If it has been exposed to biased or incomplete data, it may produce responses that are similarly flawed.

Therefore, it’s important to approach any output generated by Chat-GPT with a critical eye and to use your own judgment to determine whether the response is accurate or appropriate in a given context.

What to do when Chat-GPT fails to solve your Coding Problems?

If you’re unable to access Chat-GPT efficiently to solve coding problems, there are several alternatives that you can consider:

Use other online resources

There are plenty of other online resources available for coding help, such as Stack Overflow, GitHub, Codecademy, and many others. These resources provide tutorials, forums, and other support for a wide range of programming languages and topics.

Join online coding communities

Joining online coding communities can be helpful in getting coding help from other developers. You can join forums, chat groups, or social media platforms like Reddit, Twitter, or Discord, where you can connect with other developers and seek help.

Look for a Mentor

If you need more personalized and one-on-one help, you can hire a tutor who can guide you through your coding problems. Many online platforms offer coding tutors who can provide help and guidance on various programming languages.

Attend coding boot camps

Coding boot camps are intensive programs designed to teach coding skills in a short period. These programs offer comprehensive training and mentorship, and they can be a great option for those who want to learn to code quickly and efficiently.

Should we use Chat-GPT to solve Coding Problems? 

With all these discussions, it is normal to be at a stand-off on whether to use Chat-GPT to solve coding problems or not! 

Definitely YES!!! But proceed with Caution. 

We can solve any coding-related problem using Chat-GPT and it will even answer the query in seconds. The only thing we need to concern about is that we should provide every single required detail to the textbox In-order to get the expected results, and verify every result it generates because after all Chat-GPT is still LEARNING!



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads