You are given a 0-indexed integer arraynums containing distinct numbers, an integer start, and an integer goal. There is an integer x that is initially set to start, and you want to perform operations on x such that it is converted to goal.
You can perform the following operation repeatedly on the number x:
If 0 <= x <= 1000, then for any index i in the array (0 <= i < nums.length), you can set x to any of the following:
x + nums[i]
x - nums[i]
x ^ nums[i] (bitwise-XOR)
Note that you can use each nums[i] any number of times in any order. Operations that set x to be out of the range 0 <= x <= 1000 are valid, but no more operations can be done afterward.
Return the minimum number of operations needed to convert x = start into goal, and -1 if it is not possible.
Input & Output
Example 1 — Basic Transformation
$Input:nums = [2,3], start = 3, goal = 10
›Output:2
💡 Note:We can transform 3 → 5 (3+2) → 10 (5+3+2). Total 2 operations needed.
The key insight is that this is a shortest path problem in an unweighted graph where nodes are numbers (0-1000) and edges are the three operations. BFS guarantees finding the minimum number of operations by exploring all states level by level. Time: O(1000 × n), Space: O(1000)
Common Approaches
✓
BFS with Queue
⏱️ Time: O(1000 * n)
Space: O(1000)
Use BFS to explore all possible states level by level. Each level represents one operation. Use a queue to store current values and a visited set to avoid revisiting states. This guarantees finding the minimum number of operations.
DFS with All Possibilities
⏱️ Time: O(3^n)
Space: O(n)
Use depth-first search to explore every possible transformation. At each step, try all three operations (add, subtract, XOR) with each array element. Continue until we reach the goal or exhaust all possibilities.
BFS with Queue — Algorithm Steps
Initialize queue with start value and visited set
For each level, try all operations with all nums
Add new valid states to queue
Return operations count when goal is reached
Visualization
Tap to expand
Step-by-Step Walkthrough
1
Level 0
Start with initial value in queue
2
Level 1
Generate all possible next states
3
Level 2
Continue until goal is found
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
struct QueueNode {
int val;
int ops;
struct QueueNode* next;
};
struct Queue {
struct QueueNode* front;
struct QueueNode* rear;
};
void enqueue(struct Queue* q, int val, int ops) {
struct QueueNode* node = malloc(sizeof(struct QueueNode));
node->val = val;
node->ops = ops;
node->next = NULL;
if (q->rear == NULL) {
q->front = q->rear = node;
} else {
q->rear->next = node;
q->rear = node;
}
}
struct QueueNode* dequeue(struct Queue* q) {
if (q->front == NULL) return NULL;
struct QueueNode* node = q->front;
q->front = q->front->next;
if (q->front == NULL) q->rear = NULL;
return node;
}
int solution(int* nums, int numsSize, int start, int goal) {
if (start == goal) return 0;
struct Queue q = {NULL, NULL};
bool visited[1001] = {false};
enqueue(&q, start, 0);
visited[start] = true;
while (q.front != NULL) {
struct QueueNode* current = dequeue(&q);
for (int i = 0; i < numsSize; i++) {
int nextVals[3] = {current->val + nums[i], current->val - nums[i], current->val ^ nums[i]};
for (int j = 0; j < 3; j++) {
int nextVal = nextVals[j];
if (nextVal == goal) {
return current->ops + 1;
}
if (nextVal >= 0 && nextVal <= 1000 && !visited[nextVal]) {
visited[nextVal] = true;
enqueue(&q, nextVal, current->ops + 1);
}
}
}
free(current);
}
return -1;
}
void parseArray(const char* str, int* arr, int* size) {
*size = 0;
const char* p = str;
while (*p && *p != '[') p++;
if (*p == '[') p++;
while (*p && *p != ']') {
while (*p == ' ' || *p == ',') p++;
if (*p == ']' || *p == '\0') break;
arr[(*size)++] = (int)strtol(p, (char**)&p, 10);
}
}
int main() {
char line[1000];
fgets(line, sizeof(line), stdin);
// Parse array manually
int nums[100];
int numsSize = 0;
char* ptr = strchr(line, '[') + 1;
char* end = strchr(line, ']');
*end = '\0';
char* token = strtok(ptr, ",");
while (token != NULL) {
nums[numsSize++] = atoi(token);
token = strtok(NULL, ",");
}
int start, goal;
scanf("%d", &start);
scanf("%d", &goal);
printf("%d\n", solution(nums, numsSize, start, goal));
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
O(1000 * n)
Visit each number 0-1000 once, try n operations per number
n
2n
✓ Linear Growth
Space Complexity
O(1000)
Queue and visited set can store up to 1000 unique values
n
2n
✓ Linear Space
23.4K Views
MediumFrequency
~25 minAvg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡Explanation
AI Ready
💡 SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
💡
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
🔧
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
💡
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
💬
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
🔧
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
💡
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
🧪
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
📝
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
⚡
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
👻
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
💬
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
💡
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.